该题的思路很简单,就是对BST进行先序遍历,找到第k个数的时候返回。这里借助栈用迭代实现,递归的代码更简单,没有尝试。
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode *> cache;
TreeNode *point = root;
TreeNode *tmp;
int i = 0;
//先序遍历
while(point || !cache.empty()){
while(point){
cache.push(point);
point = point -> left;
}
if(!cache.empty()){
tmp = cache.top();
i++;
if(i == k)
return tmp -> val;
cache.pop();
point = tmp -> right;
}
}
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ny_mg/article/details/46851163