二叉树的前序,中序,后序遍历。用递归和非递归实现
来源:互联网 发布:5g网络架构 杨峰义pdf 编辑:程序博客网 时间:2024/04/30 14:51
#include<iostream>
#include<stack>using namespace std;#define MAX 100typedef struct Tree{int data;Tree*lchild;Tree*rchild;}*TREE,NODE;int i;//定义全局变量void Enter(TREE&t,int a[]);void Init(TREE &t);void Display_pre(TREE t);void Display_Pre(TREE t);void Display_mid(TREE t);void Display_Mid(TREE t);void Display_las(TREE t);void Display_Las(TREE t);int main(){TREE T=NULL;Init(T);Display_pre(T);cout<<endl;Display_Pre(T);cout<<endl<<endl;Display_mid(T);cout<<endl;Display_las(T);cout<<endl;Display_Las(T);cout<<endl;return 0;}void Enter(TREE&t,int a[]) //Init()的辅助函数,完成递归创建 {static int j=0;if(a[j++]){t=new NODE;t->data=a[j-1];t->lchild=t->rchild=NULL;Enter(t->lchild,a);Enter(t->rchild,a);}elset=NULL;}void Init(TREE &t){int a[MAX];FILE*fp;fp=fopen("C:\\Users\\Administrator\\Desktop\\asd.txt","r");i=0;while(!feof(fp)) //将内容读取到数组中 fscanf(fp,"%d",&a[i++]); Enter(t,a); cout<<"Initialize sucessfully!"<<endl;}void Display_pre(TREE t){if(t){cout<<t->data<<' ';Display_pre(t->lchild);Display_pre(t->rchild);}}void Display_mid(TREE t){if(t){Display_mid(t->lchild);cout<<t->data<<' ';Display_mid(t->rchild);}}void Display_las(TREE t){if(t){Display_las(t->lchild);Display_las(t->rchild);cout<<t->data<<' ';}}void Display_Pre(TREE t){if(!t) {cout<<"NULL!"<<endl;return;}TREE temp=t;stack<TREE> s;while((temp!=NULL)||!s.empty()){while(temp){cout<<temp->data<<' '; s.push(temp); temp=temp->lchild;}if(!s.empty()){temp=s.top();s.pop();temp=temp->rchild;}}}void Display_Mid(TREE t){if(t==NULL){cout<<"NULL!"<<endl;return;}TREE temp=t;stack<TREE> s;while((temp!=NULL)||!s.empty()){while(temp){s.push(temp);temp=temp->lchild;} if(!s.empty()) { temp=s.top(); cout<<temp->data; s.pop(); temp=temp->rchild;}}}void Display_Las(TREE t){ if(!t) { cout<<"NULL!"<<endl; return; } TREE temp=t,temp_past=NULL;//temp为当前访问的节点,temp_past为上一个访问的节点 stack<TREE>s; while(temp) //移动到最底部左子树 { s.push(temp); temp=temp->lchild; } while(!s.empty()) { temp=s.top(); s.pop(); if((temp->rchild==NULL)||(temp_past==temp->rchild)) //输出一个根节点的条件就是其右子树为空,或者其右子树已经被访问 { cout<<temp->data<<' '; temp_past=temp; } else { s.push(temp); //二次入栈 temp=temp->rchild; //进入右子树 while(temp) { s.push(temp); temp=temp->lchild;} } } }
阅读全文
1 0
- 二叉树的前序,中序,后序遍历。用递归和非递归实现
- 【二叉树】 前序、中序和后序的递归遍历与非递归遍历
- 二叉树非递归前、中、后序遍历实现
- 二叉树的遍历 前序 中序 后序 分别实现递归和非递归遍历方式
- 二叉树的前序、中序、后序遍历 递归非递归实现
- 二叉树的前序、中序、后序(递归、非递归)遍历java实现
- 二叉树的前序,中序,后序遍历(递归非递归实现)
- 实现二叉树的前序/中序/后序递归、非递归遍历
- 二叉树 前序遍历的非递归实现 中序遍历的非递归实现 后序遍历的非递归实现 创建二叉树
- 【二叉树遍历算法】——前/中/后序递归与非递归的实现
- JAVA实现二叉树的前、中、后序遍历(递归与非递归)
- 二叉树的非递归【前/中/后 序遍历】
- 数据结构:二叉树的前序,中序,后序遍历(递归和非递归)
- 二叉树的递归和非递归遍历(前序、中序、后序)
- 非递归实现二叉树的后序遍历、前序遍历、中序遍历
- 二叉树的递归和非递归前、中、后序遍历
- 数据结构---二叉树的前序、中序、后序遍历的递归和非递归 实现(C++)
- 数据结构-二叉树的前序、中序、后序遍历的递归和非递归实现
- 字母x在css中的角色
- 8.11
- 2017/8/11
- Refletion2017.8.11
- 字体图标
- 二叉树的前序,中序,后序遍历。用递归和非递归实现
- HDO 5748 Bellovin
- 第一阶段unity基础
- 说说 JAVA 代理模式
- Doo-Sabin细分算法
- 关于libsvm在MATLAB中的安装问题解答
- JD面试
- BZOJ 2190 仪仗队 (莫比乌斯反演)
- 学习日记11