每日一练(26):二叉搜索树的第k大节点


title: 每日一练(26):二叉搜索树的第k大节点

categories:[剑指offer]

tags:[每日一练]

date: 2022/02/25


每日一练(26):二叉搜索树的第k大节点

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

示例 1:

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

   3
  / \
 1   4
  \
   2

输出: 4

示例 2:

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

       5
      / \
     3   6
    / \
   2   4
  /
 1

输出: 4

限制:

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

来源:力扣(LeetCode)

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

方法一:vector递归

class Solution {
public:
    vector<int> ans;
    void dfs(TreeNode* root) {
        if (!root) {
            return;
        }
        dfs(root->left);
        ans.push_back(root->val);
        dfs(root->right);
    }

    int kthLargest(TreeNode* root, int k) {
        dfs(root);
        return ans[ans.size() - k];
    }
};

方法二:变量递归

把原本是 “左中右” 的中序遍历改成 “右中左” 的反向中序遍历

维护两个变量 count 和 res 即可。count 用来计数我们在降序的数字序列中走了几位,当走了 k 位时,就让 res 等于当前的 root -> val,然后退出 inorder 函数即可

class Solution {
public:
    // 二叉搜索树的中序遍历是递增序列 
    int  count, res;
    void dfs(TreeNode* root, int k){
        if (root == nullptr) {
            return;
        }
        dfs(root->right, k);
        count++;
        if (count == k) {
            res = root->val;
            return;
        }
        dfs(root->left, k);
    }

    int kthLargest(TreeNode* root, int k) {
        dfs(root, k);
        return res;
    }
};
posted @ 2022-02-25 10:33  hackettt  阅读(29)  评论(0编辑  收藏  举报