题目
给定一棵二叉搜索树,请找出其中第k大的节点。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
思路
思路1.中序遍历后为升序数组,取第k大的元素
思路2. 反中序遍历+计数器
时间复杂度:O(n),每个节点访问一次。
空间复杂度:O(n),取决于递归栈深度,最大不超过n。
实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// 中序遍历
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
return rightTraversal(root, k);
}
int rightTraversal(TreeNode* root, int count) {
if (root == nullptr) {
return 0;
}
if (root ->right != nullptr) {
rightTraversal(root->left, count);
}
if (--count == 0) {
return root->val;
};
if (root->left != nullptr) {
rightTraversal(root->right, count);
}
return 0;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// 反中序遍历
class Solution {
public:
int res;
int count = 0;
int kthLargest(TreeNode* root, int k) {
rightTraversal(root, k);
return res;
}
void rightTraversal(TreeNode* root, int k) {
if (root == nullptr) {
return;
}
rightTraversal(root->right, k);
if (++count == k) {
res = root->val;
return;
};
rightTraversal(root->left, k);
}
};