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

在这里插入图片描述

/**
 * 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:
    vector<int> res;
    vector<int> t(TreeNode* root)
    {
        if(root != nullptr)
        {
            res.push_back(root->val);
            t(root->left);
            t(root->right);
        }
        return res;
    }
    int kthLargest(TreeNode* root, int k) {
        vector<int> tmp = t(root);
        sort(tmp.begin(), tmp.end(), greater<int>());
        return tmp[k - 1];
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43956456/article/details/107682603