当前位置:网站首页>剑指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();
}
};
边栏推荐
猜你喜欢
随机推荐
mongodb的shell脚本
Laravel 中使用子查询
El - tree to set focus on selected highlight highlighting, the selected node deepen background and change the font color, etc
《多线程案例》阻塞队列、定时器、线程池、饿汉与懒汉模式
boot-SSE
华为设备配置BFD状态与接口状态联动
MySQL性能优化(硬件,系统配置,表结构,SQL语句)
信息学奥赛一本通T1450:Knight Moves
多线程打印ABC(继承+进阶)
请手撸5种常见限流算法!面试必备
在线开启gtid偶发hang住的问题解决
(十五)51单片机——呼吸灯与直流电机调速(PWM)
信息学奥赛一本通T1451:棋盘游戏
死锁的成因和对应的解决方案
解决登录vCenter提示“当前网站安全证书不受信任“
mysql慢查询优化
安全狗云原生安全能力全面亮相全球数字经济大会暨ISC互联网安全大会
C语言入门实战(14):选择排序
Detailed explanation of cause and effect diagram of test case design method
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】