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.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
分析:即找中序遇到的第k个结点。
/**
* 给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
* 中序遇到的第k个结点。
* @date 20160410
*/
public int kthSmallest(TreeNode root, int k) {
if(root == null){
return 0;
}else{
TreeNode node = root;
Stack stack = new Stack();
stack.push(node);
/*node表示入栈的元素,popnode表示弹栈的元素*/
while(!stack.isEmpty()){
while(node.left != null){//向左走到尽头,把最左分支的结点都入栈。
node = node.left;
stack.push(node);
}
TreeNode popnode= (TreeNode) stack.pop();//弹出栈顶元素
k--;
if(k == 0){
return popnode.val;
}
/*如果弹栈的元素有右孩子,则让其右孩子入栈,进行下一次循环*/
if(popnode.right != null){
node = popnode.right;
stack.push(node);
}
}
}
return 0;
}