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?
This question is the same as the k-th node of the offer-binary search tree, find the k-th smallest node of BST.
Using the result of BST in-order traversal is the property of ascending sequence, and it is easy to find the Kth .
non-recursive method
recursion
The Follow up of this question is more interesting, it is how the binary tree often performs insertion and deletion operations, and often performs the operation of finding the kth element, so how to quickly get to the kth smallest element? Change the structure of the node, each node stores the number of all nodes in its left subtree at the same time, so that according to the size of k and the current root node, it is possible to choose whether it is the current root or the kth element in the left subtree. Recursion of the left subtree, or the kth element is in the right subtree, requires recursion of the right subtree. log(N) time complexity.
Code
non-recursive method
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;
}