题目链接:
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
题目描述:
找出二叉查找树中第k小的节点的val。
题目分析:
还是非递归中序遍历的变形。
代码:
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> s;
int cnt=0;
while(root!=NULL){
s.push(root);
root=root->left;
}
while(!s.empty()){
TreeNode* top=s.top();
s.pop();
cnt++;
if(cnt==k){
return top->val;
}
TreeNode* ptr=top;
if(ptr->right!=NULL){
ptr=ptr->right;
while(ptr!=NULL){
s.push(ptr);
ptr=ptr->left;
}
}
}
}
};