当前位置:网站首页>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的追踪.
边栏推荐
- 最简单的idea构建微服务模块
- 360杜跃进ISC演讲:保障信创软件的可信性和安全性是信创安全体系的基础
- GeoServer入门学习:07-发布多层级TIF地图大图数据
- Centos安装Redis --使用wget
- Redis Bloom Filter
- Educational Codeforces Round 112 D. Say No to Palindromes
- 编译原理——LR(1)分析程序(C#)
- 目标检测论文 Precise detection of Chinese characters in historical documents with DRL
- AtCoder Beginner Contest 263(A~F)
- 安装sentry
猜你喜欢

单片机--IIC总线篇

SQL注入之搭建dnslog
Introduction to GeoServer: 01-Introduction
GeoServer Getting Started Learning: 06-Publishing Multi-level TIF Map Data
Flask 教程 第九章:分页

去噪论文 Beyond a Gaussian Denoiser: Residual Learning of Deep CNN for Image Denoising

jmeter简单压测

1天搞定单片机中断——基础知识大全

Notes: The difference between laravel, updateOrCreate and updateOrInsert

jmeter逻辑控制器使用
随机推荐
Protobuf框架与WebAPI
fastapi-后台任务、定时任务与消息队列
Kotlin反射
目标检测论文 Few-Shot Object Detection with Attention-RPN and Multi-Relation Detector
Kotlin annotations
Non-resolvableparent POM for xxxx: Could not find artifact xxx and ‘parent.relativePath‘ points at
The first day of a solid foundation for Kotlin
使用fontforge修改字体,只保留数字
amd和Intel的CPU到底哪个好?
window下socket(udp)控制台程序
Bluu海鲜公司推出首批实验室培育的鱼类产品
Kotlin笔记-ForEach与ForEachIndexed区别
Kotlin实用的一些框架
Solve the problem of slow speed of gradle import package
昇腾Ascend 随记 —— 昇腾 AI 的基本架构
【Voice of dreams】
昇腾Ascend 随记 —— TensorFlow 模型迁移
跨域问题 什么时候出现跨域问题 如何解决跨域问题
sudo控制用户权限实战操作
磁控胶囊胃镜:具有良好耐受性的非侵入性胃镜检查