该题的思路非常easy。就是对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;
}
}
}
};