当前位置:网站首页>剑指offer专项突击版第18天
剑指offer专项突击版第18天
2022-08-03 06:35:00 【hys__handsome】
方法一、直接中序遍历获得序列,然后查找p的下一个即可
class Solution {
public:
void inorder(TreeNode *root, vector<TreeNode*> &ls){
if(!root) return;
inorder(root->left,ls);
ls.emplace_back(root);
inorder(root->right,ls);
}
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
vector<TreeNode*> ls;
inorder(root,ls);
if(ls.back() == p) return nullptr;
for(int i = 0; i < ls.size(); i++) {
if(ls[i] == p) return ls[i+1];
}
return nullptr;
}
};
方法二、利用二叉树的性质,左子树所有子节点小于当前结点,并且右子树所有子节点大于当前子节点。
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* res = nullptr;
TreeNode *node = root;
while(node != nullptr) {
if(node->val > p->val) {
res = node; //node的值会越来越接近p,这里res实时更新结点
node = node->left;
} else {
//小于等于p结点就走right
node = node->right;
}
}
return res;
}
};
使用右中左的中序遍历即可,那么遍历获得的序列肯定就是降序的。接下来把前面累加的值加到当前结点即可。
class Solution {
public:
void inorder(TreeNode* root, int &sum) {
if(!root) return;
inorder(root->right,sum);
sum += root->val;
root->val = sum;
inorder(root->left,sum);
}
TreeNode* convertBST(TreeNode* root) {
int sum = 0;
inorder(root,sum);
return root;
}
};
求出中序遍历序列放入队列中,如果next操作就弹出队列即可。
class BSTIterator {
private:
TreeNode *root;
queue<TreeNode*> que;
public:
BSTIterator(TreeNode* root) {
this->root = root;
inorder(root);
}
int next() {
int num = que.front()->val;
que.pop();
return num;
}
bool hasNext() {
return que.size();
}
void inorder(TreeNode *root) {
if(!root) return;
inorder(root->left);
que.push(root);
inorder(root->right);
}
};
利用栈模拟中序遍历过程
class BSTIterator {
private:
TreeNode* cur;
stack<TreeNode*> stk;
public:
BSTIterator(TreeNode* root): cur(root) {
}
int next() {
while (cur != nullptr) {
stk.push(cur);
cur = cur->left;
}
cur = stk.top();
stk.pop();
int ret = cur->val;
cur = cur->right;
return ret;
}
bool hasNext() {
return cur != nullptr || !stk.empty();
}
};
边栏推荐
猜你喜欢
随机推荐
分治法求解中位数
Embedding two implementations of the torch code
戳Web3的神话?戳到铁板。
模型训练前后显卡占用对比、多卡训练GPU占用分析【一文读懂】
多线程打印ABC(继承+进阶)
2022年 SQL 优化大全总结详解
关于任命韩文弢博士代理NOI科学委员会主席的公告
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】
boot-SSE
MySQL日期和时间戳的转换
Flutter | 判断 Text 组件是否显示完
一篇文章教你写扫雷(c语言基础版)
在线开启gtid偶发hang住的问题解决
JS 预编译
FiBiNet torch reproduction
数仓埋点体系与归因实践
jvm 面试题
MySQL - 触发器
亿流量大考(1):日增上亿数据,把MySQL直接搞宕机了...
【第1天】SQL快速入门-基础查询(SQL 小虚竹)









