在二叉搜索树中查找第K大的数(C++实现)
#include<iostream>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int k,res;
int kthLargest(TreeNode* root, int k) {
this->k = k;
reverse_inorder(root);
return res;
}
void reverse_inorder(TreeNode*root)
{
if(root== NULL)
{
return;
}
reverse_inorder(root->right);
if(k==0) {
return;
}
if(--k==0)
{
res = root->val;
return;
}
reverse_inorder(root->left);
}
};