LeetCode 230 Kth Smallest Element in a BST
this is actually pretty easy, we only needs to do in order traverse, and stopped at the k step
class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root == null) return -1;
int count = 0;
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
//stack.push(cur); //we don't have to push cur in stack at this time because next while statement is ||
while(!stack.isEmpty() || cur != null){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
count = count + 1;
if(count == k){
return cur.val;
}
cur = cur.right;
}
return -1;//and even though it says: always assume k is valid, you have to consider this situation
}
}
in the mean time, you also need to know how to solve it recursively:
class Solution {
public ArrayList<Integer> inorder(TreeNode root, ArrayList<Integer> arr) {
if (root == null) return arr;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right, arr);
return arr;
}
public int kthSmallest(TreeNode root, int k) {
ArrayList<Integer> nums = inorder(root, new ArrayList<Integer>()); //just level order tranverse and get the k-1 th element.
return nums.get(k - 1);
}
}
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?
https://leetcode.com/problems/kth-smallest-element-in-a-bst/solution/

浙公网安备 33010602011771号