您的位置:首页 > 其它

二叉树的遍历--递归和非递归

2015-10-29 20:06 429 查看
PS:数据结构老师让写下二叉树的后序遍历的非递归算法,结果把所有的都写了一下

CODE

#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
typedef struct Binode
{
char data;
struct Binode *l, *r;
};
typedef struct node
{
struct Binode *x;
bool flag;
};
char ls[150];
int k;
void creat(Binode *&T)
{
char c;
c = ls[k++];
if(c == '#')
{
return ;
}
else
{
T = new Binode;
T->l = NULL;
T->r = NULL;
T->data = c;
creat(T->l);
creat(T->r);
}
}
void pre(Binode *T)///先序递归--中左右
{
if(T)
{
cout<<T->data;
pre(T->l);
pre(T->r);
}
}
void preBitree(Binode *T)///先序遍历非递归
{
stack<node*> A;
Binode *p;
p = T;
while(p || !A.empty())
{
while(p)
{
cout<<p->data;
node *q;
q = new node;
q->x = p;
A.push(q);
p =p->l;
}
if(!A.empty())
{
node *q;
q = A.top();
A.pop();
if(q->x->r)
{
p = q->x->r;
}
}
}
cout<<endl;
}
void In(Binode *T)///中序递归--左中右
{
if(T)
{
In(T->l);
cout<<T->data;
In(T->r);
}
}
void InBitree(Binode *T)///中序遍历非递归
{
stack<node*> A;
Binode *p;
p = T;
while(p || !A.empty())
{
while(p)
{
node *q;
q = new node;
q->x = p;
A.push(q);
p =p->l;
}
if(!A.empty())
{
node *q;
q = A.top();
A.pop();
cout<<q->x->data;
if(q->x->r)
{
p = q->x->r;
}
}
}
cout<<endl;
}
void post(Binode *T)///后序递归--左右中
{
if(T)
{
post(T->l);
post(T->r);
printf("%c",T->data);
}
}
void postBitree(Binode *T)///后序非递归
{
stack<node*> A;
Binode *p;
p = T;
while(p||!A.empty())
{
while(p){
node *q;
q = new node;
q->x = p;
q->flag = true;
A.push(q);
p =p->l;
}
if(!A.empty())
{
node *q;
q = A.top();
A.pop();
if(q->flag){
p = q->x->r;
if(p){
q->flag = false;
A.push(q);
}
else{
cout<<q->x->data;
}
}
else{
cout<<q->x->data;
}
}
}
cout<<endl;
}
int main()
{
while(~scanf("%s",ls))
{
k = 0;
Binode *root;
creat(root);
preBitree(root);
}
return 0;
}
/*
abc##de#g##f###
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: