面试题54. 二叉搜索树的第k大节点
给定一棵二叉搜索树,请找出其中第k大的节点。
示例 :
输入: root = [5,3,6,2,4,null,null,1], k = 3 输出: 4
输入: root = [3,1,4,null,2], k = 1 输出: 4
5
/ \
3 6
/ \
2 4
/
1
3
/ \
1 4
\
2
限制:
1 ≤ k ≤ 二叉搜索树元素个数
思路一:非递归
/**
* 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) {
stack<TreeNode*> stack;
//vector<int> nums;
int n = 0;
TreeNode* p = root;
while (p || !stack.empty()){
while (p){
stack.push(p);
p = p->right;
}
p = stack.top();
stack.pop();
//nums.push_back(p->val);
n++;
if (n == k){
return p->val;
}
p = p->left;
}
return 0;
}
};
/*20ms,26.6MB*/
思路二:递归
class Solution {
private:
int ans = 0;
int n = 0;
public:
int kthLargest(TreeNode* root, int k) {
InOrderTraverse(root, k);
return ans;
}
void InOrderTraverse(TreeNode* root, int k){
if (root == NULL){
return;
}
InOrderTraverse(root->right, k);
n++;
if (n == k){
ans = root->val;
return;
}
InOrderTraverse(root->left, k);
return;
}
};
/*16ms,26.8MB*/