当前位置 博文首页 > 中流击水,浪遏飞舟:中序遍历&&剑指 Offer 54. 二叉搜
注意:是二叉搜索树的中序遍历是递增序列,不是二叉树,普通二叉树和搜索树的性质有所差别。
/**
* 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) {
queue<TreeNode*> q;
priority_queue<int> p;
q.push(root);
while(!q.empty()){
p.push(q.front()->val);
if(q.front()->left){
q.push(q.front()->left);
}
if(q.front()->right){
q.push(q.front()->right);
}
q.pop();
}
while(--k){
p.pop();
}
return p.top();
}
};
基于性质:二叉树搜索树的中序遍历是递增序列。
参考K神:
面试题54. 二叉搜索树的第 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 ans,tmp;
int kthLargest(TreeNode* root, int k) {
tmp=k;
dfs(root);
return ans;
}
void dfs(TreeNode* root){
if(!root){
return;
}
dfs(root->right);
if(tmp==0) return; //tmp需要作为整体变量记录下来才能剪枝,作为参数会变化
if(--tmp==0) ans=root->val; //记录所求值
dfs(root->left);
}
};
cs