剑指 Offer 54. 二叉搜索树的第k大节点
这里说一下啥交二叉搜索树(有序
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉排序树
所以就是可以利用中序遍历
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
vector<int>res;
digui(root,res);
reverse(res.begin(),res.end());
return res[k-1];
}
void digui(TreeNode*root,vector<int>&res)
{
if(!root) return;
digui(root->left,res);
res.push_back(root->val);
digui(root->right,res);
}
};