二叉数前序总序后序递归与非递归实现

#define M 20
struct node{
char data;
node *l;
node *r;};
int max(int x,int y){
if(x>y)return x;
else return y;}
void create(node*&b,char a[]){
char c,i=0;
node *q[M],*p;
int top=-1;
int f;
c=a[i];
while(c!='\0'){
	switch(c)
	{case'(':top++;q[top]=p;f=1;break;
	case')':top--;break;
	case',':f=2;break;
	default:{p=(node*)malloc(sizeof(node));p->data=c;p->l=p->r=NULL;
			if(b==NULL)b=p;
			else{if(f==1){q[top]->l=p;}else q[top]->r=p;}
			}
	}
	c=a[++i];
 }
}
void dis(node *b){
if(b==NULL)return;
cout<<b->data;
if(b->l||b->r){cout<<"(";dis(b->l);if(b->r)cout<<",";dis(b->r);cout<<")";}
}
void preorder(node *b){
	if(b!=NULL)
	{cout<<b->data;
	preorder(b->l);
	preorder(b->r);}
}
void pre(node *b){
node *q[M];
int top=-1;
node *p=b;
if(b==NULL)return;
top++;
q[top]=b;
while(top>-1)
{   p=q[top];
top--;
cout<<p->data<<" ";
	if(p->r){top++;q[top]=p->r;}
if(p->l){top++;q[top]=p->l;}
}
}
void inorder(node*b){
if(b==NULL)return ;
inorder(b->l);
cout<<b->data;
inorder(b->r);
}
void in(node*b){
node *q[M],*p;
int top=-1;
if(b==NULL)return ;
p=b;
while(top>-1||p){
	while(p){top++;q[top]=p;p=p->l;}
	if(top>-1){p=q[top];top--;cout<<p->data;p=p->r;}
}
}
void postorder(node *b){
if(b==NULL)return ;
postorder(b->l);
postorder(b->r);
cout<<b->data;
}
void post(node *b){
node*q[M],*p,*p1;
int top=-1;
int f;
if(b==NULL)return;
p=b;
while(top>-1||p)
{while(p){top++;q[top]=p;p=p->l;}
p1=NULL;
f=1;
while(top>-1&&f){
  p=q[top];
  if(p->r==NULL||p->r==p1){cout<<p->data;top--;p1=p;}
  else{p=p->r;f=0;}
  }
if(top==-1)break;}
}

你可能感兴趣的:(二叉数前序总序后序递归与非递归实现)