C语言二叉树的非递归遍历实例分析
作者:shichen2014 时间:2022-02-08 02:41:15
本文以实例形式讲述了C语言实现二叉树的非递归遍历方法。是数据结构与算法设计中常用的技巧。分享给大家供大家参考。具体方法如下:
先序遍历:
void preOrder(Node *p) //非递归
{
if(!p) return;
stack<Node*> s;
Node *t;
s.push(p);
while(!s.empty())
{
t=s.top();
printf("%d\n",t->data);
s.pop();
if(t->right) s.push(t->right);
if(t->left) s.push(t->left);
}
}
中序遍历:
void inOrder(Node *p)
{
if(!p)
return;
stack< pair<Node*,int> > s;
Node *t;
int unUsed;
s.push(make_pair(p,1));
while(!s.empty())
{
t=s.top().first;
unUsed = s.top().second;
s.pop();
if(unUsed)
{
if(t->right)
s.push( make_pair(t->right,1) );
s.push( make_pair(t,0) );
if(t->left)
s.push( make_pair(t->left,1));
}
else printf("%d\n",t->data);
}
}
后序遍历:
void postOrder(Node *p)
{
if(!p) return;
stack<pair<Node*,int> > s;
Node *t;
int unUsed;
s.push(make_pair(p,1));
while(!s.empty())
{
t=s.top().first;
unUsed=s.top().second;
s.pop();
if(unUsed)
{
s.push(make_pair(t,0);
if(t->right)
s.push(make_pair(t->right,1));
if(t->left)
s.push(make_pair(t->left,1));
}
else printf("%d\n",t->data);
}
}
希望本文所述对大家C程序算法设计的学习有所帮助。
标签:C语言,二叉树
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
一文详解Java线程的6种状态与生命周期
2022-02-08 08:44:30
![](https://img.aspxhome.com/file/2023/5/122955_0s.jpg)
Android实现中轴旋转特效 Android制作别样的图片浏览器
2023-07-03 00:37:16
![](https://img.aspxhome.com/file/2023/2/104662_0s.png)
详解Spring Cloud Stream使用延迟消息实现定时任务(RabbitMQ)
2022-09-14 05:07:34
![](https://img.aspxhome.com/file/2023/5/72905_0s.png)
深入理解Java设计模式之抽象工厂模式
2023-11-28 12:11:34
![](https://img.aspxhome.com/file/2023/6/60336_0s.jpg)
SpringBoot整合Mybatis自定义拦截器不起作用的处理方案
2023-03-19 04:35:14
![](https://img.aspxhome.com/file/2023/7/77937_0s.png)
Flutter ListView 上拉加载更多下拉刷新功能实现方法
2023-06-25 19:51:57
![](https://img.aspxhome.com/file/2023/4/89604_0s.gif)
关于idea中ssm框架的编码问题分析
2023-06-03 04:40:21
![](https://img.aspxhome.com/file/2023/9/77369_0s.jpg)
解决jasperreport导出的pdf每页显示的记录太少问题
2023-04-14 13:02:01
![](https://img.aspxhome.com/file/2023/0/77080_0s.jpg)
Java Controller实现参数验证与统一异常处理流程详细讲解
2022-01-25 18:49:47
SpringBoot使用AOP与注解实现请求参数自动填充流程详解
2022-08-18 17:30:36
详解JAVA Spring 中的事件机制
2022-01-13 05:26:33
c#基于NVelocity实现代码生成
2023-06-03 14:46:18
![](https://img.aspxhome.com/file/2023/8/113828_0s.png)
android studio 3.0 service项目背景音乐实现
2023-07-03 23:34:36
![](https://img.aspxhome.com/file/2023/9/116159_0s.png)
如何在C#中使用OpenCV(GOCW使用教程)
2023-09-09 23:39:30
![](https://img.aspxhome.com/file/2023/3/123903_0s.png)
springboot 在idea中实现热部署的方法
2022-10-24 22:27:19
![](https://img.aspxhome.com/file/2023/8/70518_0s.png)
JAVA用递归实现全排列算法的示例代码
2023-06-01 09:09:58
Android studio实现简易计算器App功能
2023-03-07 07:57:57
![](https://img.aspxhome.com/file/2023/0/98620_0s.jpg)
Java上传视频实例代码
2023-06-24 04:17:45
SpringCloud如何创建一个服务提供者provider
2023-08-01 01:56:33
![](https://img.aspxhome.com/file/2023/3/57813_0s.png)
java虚拟机深入学习之内存管理机制
2023-07-03 21:15:40
![](https://img.aspxhome.com/file/2023/5/101785_0s.png)