头图

title: Daily practice (26): the kth largest node of the binary search tree

categories:[Swords offer]

tags:[Daily practice]

date: 2022/02/25


Daily practice (26): the kth largest node of the binary search tree

Given a binary search tree, find the value of the kth largest node in it.

Example 1:

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

   3
  / \
 1   4
  \
   2

Output: 4

Example 2:

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

       5
      / \
     3   6
    / \
   2   4
  /
 1

Output: 4

limit:

1 ≤ k ≤ number of elements in binary search tree

Source: LeetCode

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

Method 1: vector recursion

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];
    }
};

Method 2: Variable recursion

Change the in-order traversal of "left-center-right" to reverse in-order traversal of "right-center-left"

It is enough to maintain two variables count and res. count is used to count how many digits we have walked in the descending sequence of numbers. When k digits have been moved, let res equal to the current root -> val, and then exit the inorder function.

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;
    }
};

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记