Sword Finger Offer Interview Question 54: The k-th largest node of the binary search tree

This question can be traversed directly in the middle order.

 

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);
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/114986216