LeetCode OJ 230. Kth Smallest Element in a BST

时间:2022-01-23 20:38:16
Total Accepted: 46445 Total Submissions: 122594 Difficulty: Medium

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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

二叉搜索树特点是对于任意一个节点,它的左子树的节点值都比它小,它的右子树的值都比它大。因此可以从树的最左边向上递归,同时计数,直到计数达到当前指定数字。
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int cnt = 0;
public int kthSmallest(TreeNode root, int k) {
int result = 0;
if(root != null){
result = kthSmallest(root.left,k);
cnt++;
if(cnt == k){
return root.val;
}
result += kthSmallest(root.right,k);
}
return result;
}
}