Sword refers to Offer54-the k-th largest node of the binary search tree-easy

Question link

Title description:

Given a binary search tree, please find the k-th largest node in it.

For example, enter:

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

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

data range:

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

Problem-solving ideas:

In a binary search tree, all nodes in the left subtree are smaller than the root node, and all nodes in the right subtree are larger than the root node. All nodes in the left and right subtrees meet this rule.
The middle order traversal sequence of the binary search tree is an increasing sequence. But what this question wants is the k-th largest node. Therefore, the reverse order of the middle order traversal is required.
Recursive traversal sequence: 1. Right subtree 2. Root node 3. Left subtree
Use a num to record the current number of values. When num == k, the recursion can be terminated early.

AC code (c++)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    void dfs(TreeNode * root,int k,int &num,int &ans){
    
    
        if(!root)
            return;
        dfs(root->right,k,num,ans);
        num++;
        if(num==k)
        {
    
    
            ans = root->val;
            return;
        }
        dfs(root->left,k,num,ans);
        
        
    }
    int kthLargest(TreeNode* root, int k) {
    
    
        int ans=0;
        int num=0;
        dfs(root,k,num,ans);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/113049112