Sword refers to Offer 54. The k-th largest node of the binary search tree (recursive)

Insert picture description here
The naive idea is to use the list to save to find the Kth in
reverse order traversal, but it is too troublesome . Recursive thinking is to traverse to the Kth order when traversing in reverse order and return directly to the Kth.

    int res = 0;
    int k;
    public int kthLargest(TreeNode root, int k) {
    
    
        this.k = k;
        disIn(root);
        return res;
    }
    void disIn(TreeNode root){
    
    //反中序遍历
        if (k < 1 || root == null) return ;//已经找到第K个
        kthLargest(root.right,k);//找到最右侧
        if (k == 1){
    
    //第K大
            res = root.val;
        }
        k--;//遍历的元素个数
        kthLargest(root.left,k);
    }

Guess you like

Origin blog.csdn.net/qq_43434328/article/details/115148900