数据结构和算法

二叉搜索树 - LeetCode 54.二叉搜索树的第k大节点

2023-12-12  本文已影响0人  我阿郑

给定一棵二叉搜索树,找出其第 k 大的节点的值。(1≤k≤N ,N为二叉搜索树节点个数)

image.png
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(this.k == 0) return;
        if(--this.k == 0) res = root.val;
        dfs(root.left);
    }
}
image.png

✅ 230. 二叉搜索树中第 K 小的元素

image.png
class Solution {
    int res, k;
        public int kthSmallest(TreeNode root, int k) {
        this.k = k;
        dfs(root);
        return res;
    }
    void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        if (k == 0) return;
        if (--k == 0) res = root.val;
        dfs(root.right);
    }
}
上一篇下一篇

猜你喜欢

热点阅读