![](https://i-blog.csdnimg.cn/blog_migrate/555877b94d67eb17f99813da40f4ebfd.png)
递归1:
/**
* 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 res=0;
int k;
void fun(TreeNode* root){
if(root==nullptr) return;
fun(root->right);
k--;
if(k==0){
res = root->val;
}
fun(root->left);
}
int kthLargest(TreeNode* root, int k) {
this->k = k;
fun(root);
return res;
}
};
递归2:
/**
* 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) {
if(root==nullptr)return 0;
vector<int>vec;
helper(root,vec);
return vec[vec.size()-k];
}
void helper(TreeNode* root,vector<int> &vec){
if(root==nullptr) return ;
helper(root->left,vec);
vec.push_back(root->val);
helper(root->right,vec);
}
};