题目
思路
遍历树 val 放入 vector ,然后排序输出第 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:
int kthLargest(TreeNode* root, int k) {
vector<int> res;
if (root == NULL) return 0;
dfs(root,res);
sort(begin(res), end(res));
return res[size(res) - k];
}
void dfs(TreeNode* root, vector<int> &res)
{
if (root == NULL) return ;
res.push_back(root->val);
dfs(root->left,res);
dfs(root->right,res);
}
};