#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}bintnode;
typedef struct stack
{
bintnode *data[100];
int tag[100];
int top;
}seqstack;
void push(seqstack *s,bintnode *t)
{
s->data[s->top]=t;
s->top++;
}
bintnode *pop(seqstack *s)
{
if(s->top!=0)
{
s->top--;
return (s->data[s->top]);
}
else
{
return NULL;
}
}
int d=0;
bintnode *createtree()/*按照前序遍历创建一个二叉树*/
{
char ch;
bintnode *t;
if((ch=getchar())==' ')
t=NULL;
else
{
t=(bintnode*)malloc(sizeof(bintnode));
t->data=ch;
t->lchild=createtree();
t->rchild=createtree();
}
return t;
}
void compute(bintnode *t)/*前序遍历计算叶子节点个数*/
{
if(t)
{
if(t->lchild==NULL&&t->rchild==NULL)
d++;
compute(t->lchild);
compute(t->rchild);
}
}
void ino1(bintnode *t)/*中序遍历*/
{
if(t)
{
ino1(t->lchild);
printf("%c ",t->data);
ino1(t->rchild);
}
}
void pos1(bintnode *t)
{
if(t)
{
pos1(t->lchild);
pos1(t->rchild);
printf("%c ",t->data);
}
}
void pre1(bintnode *t)
{
if(t)
{
printf("%c ",t->data);
pre1(t->lchild);
pre1(t->rchild);
}
}
//--------------------------------------------------
void pre2(bintnode *t)//前序遍历
{
seqstack s;
s.top=0;
while((t)||(s.top)!=0)
{
if(t)
{
printf("%c ",t->data);
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
t=t->rchild;
}
}
}
void ino2(bintnode *t)//中序遍历
{
seqstack s;
s.top=0;
while((t!=NULL)||(s.top!=0))
{
if(t)
{
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
printf("%c ",t->data);
t=t->rchild;
}
}
}
void pos2(bintnode *t)//后序遍历
{
seqstack s;
s.top=0;
while((t)||(s.top!=0))
{
if(t)
{
s.data[s.top]=t;
s.tag[s.top]=0;
s.top++;
t=t->lchild;
}
else if(s.tag[s.top-1]==1)
{
s.top--;
t=s.data[s.top];
printf("%c ",t->data);
t=NULL;
}
else
{
t=s.data[s.top-1];
s.tag[s.top-1]=1;
t=t->rchild;
}
}
}
int main()
{
bintnode *t;
t=(bintnode*)malloc(sizeof(bintnode));
printf("请创建二叉树:");
t=createtree();
printf("\n叶子节点个数:");
compute(t);
printf("%d",d);
printf("\n------------------------------\n");
printf("\n递归");
printf("\n前序遍历:");
pre1(t);
printf("\n中序遍历:");
ino1(t);
printf("\n后序遍历:");
pos1(t);
printf("\n-----------------------------\n");
printf("非递归");
printf("\n前序遍历:");
pre2(t);
printf("\n中序遍历:");
ino2(t);
printf("\n后序遍历:");
pos2(t);
printf("\n");
return 0;
}