当前位置:网站首页>二叉树前序遍历、中序遍历、后序遍历的迭代版
二叉树前序遍历、中序遍历、后序遍历的迭代版
2022-08-08 20:54:00 【三十而学】
二叉树前序遍历、中序遍历、后序遍历的迭代版
- 前序遍历
void preorder(TreeNode* root)
{
if(root==NULL)
return;
stack<TreeNode*> s;
while(root||!s.empty())
{
while(root)
{
//...处理root
s.push(root);
root=root->left;
}
root=s.top();
s.pop();
root=root->right;
}
}
- 中序遍历
void midorder(TreeNode* root)
{
if(root)
cout<<"empty!"<<endl;
stack<int> s;
while(root||!s.empty())
{
while(root)
{
s.push(root);
root=root->left;
}
root=s.top();
s.pop();
//...处理root
root=root->right;
}
}
- 后序遍历
void postorder(TreeNode* root)
{
stack<TreeNode*> s;
TreeNode * p = root;
TreeNode * lastVisited = NULL;//记录上一次访问过的节点
if(p == NULL)
return ans;
while(!s.empty() || p)
{
//不断往左孩子迭代,直到左孩子为空,同时路径上的节点入栈
if(p)
{
s.push(p);
p = p->left;
}
//此时p==NULL,到达了左下角节点
else
{
p = stk.top();
//右孩子为空,或者右孩子上次已经访问完
if(p->right == NULL || p->right == lastVisited)
{
//...处理p
lastVisited = p;//更新lastVisited
s.pop();
p = NULL;
}
else{
p = p->right;//这时p是第一次被访问,不能直接访问其指向的值,应该先访问右子树
}
}
}
return ans;
}
前序遍历和中序遍历基本一样,访问节点位置不一样,后序遍历相对复杂,关键在于lastvisited的追踪。
边栏推荐
- Bluu Seafood launches first lab-grown fish products
- 解决gradle导包速度慢问题
- Fastdata极数:元宇宙报告2022——Hello Metaverse
- Kotlin study notes
- Kotlin's JSON format parsing
- The new database is online | CnOpenData information transmission, software and information technology service industry basic information data of industrial and commercial registered enterprises
- 随手记:laravel、updateOrCreate 和 updateOrInsert 的区别
- 单片机——串口通信(从串口接收多位数据保存到数组,发送多位数据到串口)
- 语义分割FCN FPN UNet DeepLab HRNet SETR TransFuse...
- 磁控胶囊胃镜:具有良好耐受性的非侵入性胃镜检查
猜你喜欢
随机推荐
drf-树形结构的model的序列化显示
究竟什么才是“云计算” | 科普好文
一下科技:未来短视频行业发展呈四大趋势
Fastdata极数:元宇宙报告2022——Hello Metaverse
单片机--IIC总线篇
Questions about Mac terminal custom commands and Mysql command
C#实现Everything——UI与查询 附源码
Mendix:企业成功执行数字化转型的9个因素
Redis布隆过滤器
澳洲ABM创新模式将销售代理权给到个体,让利消费者
莫让“学院派”限制我们的思维:在数组的中间位置删除数据一定比链表慢?
源码分析MyCat专栏
fastapi-实战-综述
门外汉掌握数据分析处理技术的路线图
Kotlin解析String路径小知识
源码分析Canal专栏
暑期“小候鸟”超员增多 惠州交警提醒:安全出行不能忘
Flask 教程 第二章:模板
头条二面:你确定ThreadLocal真的会造成内存泄露?
SQL注入之搭建dnslog