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

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

题目

链接

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

问题描述

给定一棵二叉搜索树,请找出其中第 k 大的节点的值。

示例

输入: root = [3,1,4,null,2], k = 1
3
/
1 4

  2
输出: 4

提示

1 ≤ k ≤ 二叉搜索树元素个数

思路

直接右中左,新建count来记录数,找到第k个存储。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(1)

代码

Java

    public static int ans;
    public static int count=0;

    public static int kthLargest(TreeNode root, int k) {
        if (root == null) {
            return -1;
        }
        dfs(root, k);
        return ans;
    }

    public static void  dfs(TreeNode root, int k) {
        if(root == null) {
            return;
        }
        dfs(root.right, k);
        count++;
        if(count == k) {
            ans = root.val;
        }
        dfs(root.left, k);
    }
posted @ 2022-03-20 22:50  cheng102e  阅读(23)  评论(0编辑  收藏  举报