Given a binary search tree, write a functionkthSmallest
to find thekth 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?
Credits:
Special thanks to@tsfor adding this problem and creating all test cases.
tag: DFS, Binary Tree, In Order Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int count = 0;
int ans = -1;
public int kthSmallest(TreeNode root, int k) {
dfs(root, k);
return ans;
}
private void dfs(TreeNode root, int k){
if (root == null) return;
dfs(root.left, k);
count++;
if (count == k) ans = root.val;
dfs(root.right, k);
}
}