Sword refers to Offer 54. The k-th largest node of the binary search tree

Sword refers to Offer 54. The k-th largest node of the binary search tree
Here is what cross-binary search tree (ordered
if its left subtree is not empty, the value of all nodes on the left subtree is less than its root The value of the node;
if its right subtree is not empty, the values ​​of all nodes on the right subtree are greater than the value of its root node;
its left and right subtrees are also binary sorted trees,
so it is In-order traversal

class Solution {
    
    
public:
    int kthLargest(TreeNode* root, int k) {
    
    
        vector<int>res;
        digui(root,res);
        reverse(res.begin(),res.end());
        return res[k-1];
        
    }
    void digui(TreeNode*root,vector<int>&res)
    {
    
    
        if(!root) return;
        digui(root->left,res);
        res.push_back(root->val);
        digui(root->right,res);
        
    }
};

Guess you like

Origin blog.csdn.net/qq_44808694/article/details/111418491