Loading

剑指 Offer 54. 二叉搜索树的第k大节点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res,k;
    public int kthLargest(TreeNode root, int k) {
        this.k = k;
        dfs(root);
        return res;
    }

    void dfs(TreeNode root){
        if(root == null) return;
        dfs(root.right);
        if(--k==0){
            res = root.val;
            return;
        }

        dfs(root.left);

    }
}
posted @ 2021-04-11 15:41  想用包子换论文  阅读(29)  评论(0编辑  收藏  举报