Given a binary search tree, write a function kthSmallest to find the kth smallest
element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
找到二叉搜索树中的第k小的元素。
使用栈,如果有左子树,入栈,否则出栈,k--,k=0则当地节点就是要找的节点,
否则寻找右子树。
因为最小的点在最左下,所以一直操作左子树。
public class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode p=root;
while(p!=null||!stack.isEmpty()){
if(p!=null){
stack.push(p);
p=p.left;
}else{
TreeNode t=stack.pop();
k--;
if(k==0)
return t.val;
p=t.right;
}
}
return 0;
}
}