题目链接:剑指 Offer 54. 二叉搜索树的第k大节点
方法一:中序遍历成递增数组
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) { //中序遍历 从小到大排序
if (root == nullptr) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int kthLargest(TreeNode* root, int k) {
vector<int> res;
inorder(root, res);
return res[res.size() - k];
}
};
方法二:修改中序遍历,成递减数组,并在递归上加一句判断,使得数组最后一个元素就是第k大
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res, int k) { //修改中序遍历 从大到小排序
if (res.size() == k) return; //加了一个判断 我们只需要找第k大数字 后面的就不需要了
if (root == nullptr) return;
inorder(root->right, res, k);
res.push_back(root->val);
inorder(root->left, res, k);
}
int kthLargest(TreeNode* root, int k) {
vector<int> res;
inorder(root, res, k);
return res[k - 1]; //索引需要-1 第1大时索引0
}
};