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.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
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?
Solution:
中序遍历,第K个遍历的就是Kth largest node,根据BST的特性,左子树 < current < 右子树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
if (root == null) {
return 0;
}
int[] count = { k };
int[] target = { -1 };
kthSmallestHelper (root, target, count);
return target[0];
}
private void kthSmallestHelper (TreeNode root, int[] target, int[] count) {
if (root == null) {
return;
}
if (root.left != null) {
kthSmallestHelper (root.left, target, count);
}
count[0] --;
if (count[0] == 0) {
target[0] = root.val;
return;
}
if (root.right != null) {
kthSmallestHelper (root.right, target, count);
}
}
}