剑指Offer面试题54:二叉搜索树的第k大节点

这道题,直接中序遍历就行

class Solution {
    int i = 0;
    int res = 0;
    public int kthLargest(TreeNode root, int k) {
        midTree(root, k);
        return res;
    }
    public void midTree(TreeNode root, int k){
        if(root.right!=null){
            midTree(root.right, k);
        }
        
        i++;
        if(i == k){
            res =  root.val;
        }
        if(root.left!=null){
             midTree(root.left, k);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114986216