当前位置:网站首页>Iterative version of preorder traversal, inorder traversal, and postorder traversal of binary tree
Iterative version of preorder traversal, inorder traversal, and postorder traversal of binary tree
2022-08-08 21:03:00 【Thirty to learn】
二叉树前序遍历、中序遍历、Iterative version of post-order traversal
- 前序遍历
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;//Record the last visited node
if(p == NULL)
return ans;
while(!s.empty() || p)
{
//Keep iterating to the left child,直到左孩子为空,At the same time, the nodes on the path are pushed onto the stack
if(p)
{
s.push(p);
p = p->left;
}
//此时p==NULL,Reached the lower left corner node
else
{
p = stk.top();
//右孩子为空,Or the right child has already visited the last time
if(p->right == NULL || p->right == lastVisited)
{
//...处理p
lastVisited = p;//更新lastVisited
s.pop();
p = NULL;
}
else{
p = p->right;//这时p是第一次被访问,The value it points to cannot be accessed directly,should visit the right subtree first
}
}
}
return ans;
}
Preorder traversal is basically the same as inorder traversal,The access node location is different,Post-order traversal is relatively complex,关键在于lastvisited的追踪.
边栏推荐
- 【导出PDF-项目应用】
- wp-ctfshow-web10 (group up注入)
- 快照集成(Snapshot Ensemble)
- [MEF]第04篇 MEF的多部件导入(ImportMany)和目录服务
- 各类测试场景的检查点
- 阿里云祝顺民:算力网络架构的新探索
- [MEF] Chapter 04 MEF's Multi-Component Import (ImportMany) and Directory Services
- 磁控胶囊胃镜:具有良好耐受性的非侵入性胃镜检查
- The new library online | CnOpenDataA shares of the listed company basic information data
- 最简单的idea构建微服务模块
猜你喜欢
随机推荐
Flask 教程 第十一章:美化
【线性代数05】行列式的性质和应用
【JVM内存区域】
Use fontforge to modify font, keep only numbers
究竟什么才是“云计算” | 科普好文
GeoServer入门学习:07-发布多层级TIF地图大图数据
Centos下载安装redis- 使用yum
Questions about Mac terminal custom commands and Mysql command
[MEF]第05篇 MEF的目录(Catalog)筛选
目标检测论文 Bridng the Gap Between Anchor-based and Anchor-free Detection via ATSS
amd和Intel的CPU到底哪个好?
语义分割FCN FPN UNet DeepLab HRNet SETR TransFuse...
ssh 登录connectction reset by peer
window下socket(TCP)控制台程序
Gradle is as simple as using kotlin to write common commands
Simple Swing interface notes
Jenkins下载安装
第十三届蓝桥杯(Web 应用开发)线上模拟赛【第十题】(RESTful API 开发)
Mysql management commands
Flask 教程 第七章:错误处理