15.二叉搜索树第k小元素

373 阅读1分钟

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

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

image.png

class Solution {
    private int count;
    private int ans;
    public int kthSmallest(TreeNode root, int k) {
       //中序遍历一棵二叉搜索树,就是你排序之后的结果.求第k小,实际上就是求排序后的第k个,也就是第k个中序遍历遍历到的节点
        count = k;
        ldr(root);
        return ans;
        
    }
    private void ldr(TreeNode root){
        //递归先写推出条件
        if(root == null || count == 0){
            return ;
        }
        ldr(root.left);
        if(--count == 0){
            ans = root.val;
        }
        ldr(root.right);
    }
}