230. 二叉搜索树中第K小的元素

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

进阶:
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?

 
class Solution {
    public int kthSmallest(TreeNode root, int k) {
     int num = count(root.left);   
        if(num >=k){
            return kthSmallest(root.left,k);
        }else if(num + 1<k){
            return kthSmallest(root.right,k-num-1);
        }
        return root.val;
    }
    
    public int count(TreeNode root){
        if(root == null){
            return 0;
        }
        return 1 + count(root.left) + count(root.right);
    }
}

  

原文地址:https://www.cnblogs.com/Stefan-24-Machine/p/10887973.html