当前位置:网站首页>二叉树的前序,中序,后续(非递归版本)
二叉树的前序,中序,后续(非递归版本)
2022-07-01 15:36:00 【努力变好的zz】
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
二叉树的非递归版本的前序中序后序在面试中也经常考,必须熟练掌握!
下面将会讲如何非递归打印二叉树的前中后序。
一、前序
思路:递归改非递归一般都要用到数据结构栈,当前节点出栈的时候打印,并有右节点先加入右节点,
后加入左节点,因为前序根左右,而栈是逆序,所以先入有节点。
void Print(TreeNode* root)
{
//前序
stack<TreeNode*> s = stack<TreeNode*>();//创建栈
s.push(root);//头结点入栈
入栈顺序有右压右,有左压左
while (!s.empty())
{
TreeNode* cur = s.top();
s.pop();
cout << to_string(cur->val)+"" ;
if (cur->right)
{
s.push(cur->right);
}
if (cur->left)
{
s.push(cur->left);
}
}
}
二、后序
思路:与前序不同,后序我们需要两个栈进行调换,第一个栈得出的结果顺序是根右左,因为栈逆序,我们将s1栈中的数据放入s2就得到了左右根,后续操作和前序相似。
后序
stack<TreeNode*> s1 = stack<TreeNode*>();
stack<TreeNode*> s2 = stack<TreeNode*>();
s1.push(root);
while (!s1.empty())
{
TreeNode* cur = s1.top();
s1.pop();
s2.push(cur);
if (cur->left)
{
s1.push(cur->left);
}
if (cur->right)
{
s1.push(cur->right);
}
}
while (!s2.empty())
{
TreeNode* cur = s2.top();
s2.pop();
cout << cur->val << endl;
}
三、中序
代码如下:
中序
stack<TreeNode*> t = stack<TreeNode*>();
TreeNode* cur = root;
while (!t.empty() || cur!=nullptr)
{
if (cur!= nullptr)
{
t.push(cur);
cur = cur->left;
}
else
{
cur = t.top();
t.pop();
cout << cur->val << endl;
cur = cur->right;
}
}
总结
边栏推荐
- 如何实现时钟信号分频?
- Qt+pcl Chapter 9 point cloud reconstruction Series 2
- Junda technology - wechat cloud monitoring scheme for multiple precision air conditioners
- Tableapi & SQL and MySQL insert data of Flink
- 采集数据工具推荐,以及采集数据列表详细图解流程
- 【天线】【3】CST一些快捷键
- Flink 系例 之 TableAPI & SQL 与 MYSQL 数据查询
- 【云动向】6月上云新风向!云商店热榜揭晓
- 《QT+PCL第六章》点云配准icp系列3
- C#/VB.NET 合并PDF文档
猜你喜欢
Deep operator overloading (2)
Raytheon technology rushes to the Beijing stock exchange and plans to raise 540million yuan
【一天学awk】条件与循环
雷神科技冲刺北交所,拟募集资金5.4亿元
Intelligent operation and maintenance practice: banking business process and single transaction tracking
Stm32f4-tft-spi timing logic analyzer commissioning record
STM32F4-TFT-SPI时序逻辑分析仪调试记录
【ROS进阶篇】第五讲 ROS中的TF坐标变换
Skywalking 6.4 distributed link tracking usage notes
Pnas: brain and behavior changes of social anxiety patients with empathic embarrassment
随机推荐
Implementation of deploying redis sentry in k8s
精益六西格玛项目辅导咨询:集中辅导和点对点辅导两种方式
【一天学awk】条件与循环
6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
Opencv Learning Notes 6 -- image feature [harris+sift]+ feature matching
MySQL审计插件介绍
Rhcsa fourth day operation
有些能力,是工作中学不来的,看看这篇超过90%同行
The solution to turn the newly created XML file into a common file in idea
Flink 系例 之 TableAPI & SQL 与 MYSQL 插入数据
Introduction to MySQL audit plug-in
k8s部署redis哨兵的实现
使用swiper制作手机端轮播图
Survey of intrusion detection systems:techniques, datasets and challenges
做空蔚来的灰熊,以“碰瓷”中概股为生?
Qt+pcl Chapter 9 point cloud reconstruction Series 2
关于用 ABAP 代码手动触发 SAP CRM organization Model 自动决定的研究
Redis high availability principle
《QT+PCL第六章》点云配准icp系列2
Qt+pcl Chapter 6 point cloud registration ICP Series 2