剑指 Offer 54 二叉搜索树的第k大节点
概述
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
中序遍历
实现的时候注意,count 放全局变量好搞一些。
class Solution {
public:
int i = 0;
int k;
int ans = -1;
int count = 0;
int kthLargest(TreeNode* root, int k) {
this->k = k;
helper(root);
return ans;
}
void helper(TreeNode* root) {
if (count >= k) return;
if (!root) return;
helper(root->right);
count ++;
if (count == k) {
ans = root->val;
return;
}
helper(root->left);
}
};
Links: sword-offer-54