Leetcode 230. Kth Smallest Element in a BST

题目链接

https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

题目描述

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?

题解

最直接的方法就是中序遍历,得到有序数组,然后取得第k个值;
也可以使用二分法,因为平衡二叉树以根节点分为左右两部分,我们可以统计左边节点的个数,然后与k值相比较,如果大于k值,说明第k个值在左子树上,否则在当前节点或者右子树。递归遍历即可。

代码

/**
 * 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) {
        int count = countNodes(root.left);
        if (k <= count) {
            return kthSmallest(root.left, k);
        } else if (k > count + 1) {
            return kthSmallest(root.right, k - 1 - count);
        }
        return root.val;
    }
    
    public int countNodes(TreeNode n) {
        if (n == null) { return 0; }
        return 1 + countNodes(n.left) + countNodes(n.right);
    }
}