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?
该题的 Follow up 比较有意思,说是如何该二叉树经常进行插入删除操作,也经常进行找到第k个元素的操作,那么如何快速的到第k小的元素? 改变节点的结构,每一个节点同时存储它的左子树所有节点数目,这样便可以根据 k 与 当前根节点的大小,来选择恰好是当前根,还是第k个元素在左子树中,需递归左子树,或者第k个元素在右子树中,需递归右子树。 log(N)的时间复杂度。
代码实现
非递归法
public int kthSmallest(TreeNode root, int k) {
if (root ==null|| k <=0) {
return0;
}
Stack<TreeNode>stack=newStack<>();
TreeNode curNode = root;
while (curNode !=null||!stack.isEmpty()) {
while (curNode !=null) {
stack.push(curNode);
curNode = curNode.left;
}
curNode =stack.pop();
//看是否到第k个节点了if (--k ==0) {
return curNode.val;
}
curNode = curNode.right;
}
return0;
}