思路
二叉搜索树的中序遍历就是将所有节点从小到大排列,那么如果是从大到小排列,第k个节点就是第k大的节点了。因此在中序遍历的过程中只要先遍历右子树,后遍历左子树即可。
class Solution {
private:
int count = 0, res = 0;
public:
void inorder(TreeNode* root, int k) {
if (root == nullptr) return;
inorder(root->right, k);
++count;
if(count == k) {
res = root->val;
return;
}
inorder(root->left, k);
}
int kthLargest(TreeNode* root, int k) {
inorder(root, k);
return res;
}
};