思路:
第k大的数字就是倒序的第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 ans;
int k;
int kthLargest(TreeNode* root, int _k) {
k = _k;
dfs(root);
return ans;
}
void dfs(TreeNode* root){
if(!root) return;
dfs(root->right);
if(--k == 0) ans = root->val;
dfs(root->left);
}
};
评论区