//创建结构体
typedef struct bin{
char a;
struct bin *lchild;
struct bin *rchild;
}tree;
//递归输入数据
tree *create()
{
tree p;
char b=getchar();
if(b==’@’)
return NULL;
else
{
p=(tree)malloc(sizeof(tree));
p->a=b;
p->lchild=create();
p->rchild=create();
}
return p;
}
递归前序遍历
void qian()
{
tree *p;
printf("%c",p->a);
p->lchild=qian();
p->rchild=qian();
}
递归中序遍历
void zhong()
{
tree *p;
p->lchild=zhong();
printf("%c",p->a);
p->rchild=zhong();
}
递归后续遍历
void hou()
{
tree *p;
p->lchild=hou();
p->rchild=hou();
printf("%c",p->a);
}
非递归前序遍历
void qian ()
{
tree *p,*n[20];
int top=-1;
p=n[++top];
while(p!=NULL)
{
printf("%c",p->a);
p=n[top–];
if(top>-1)
n[++top]=p->rchild;
if(top>-1)
n[++top]=p->lchild;
}
}
非递归中序遍历
void zhong()
{
tree *p1,*n[20];
int top=-1;
n[++top]=p1;
while(p1!=NULL&&top>-1)
{
while(p1!=NULL)
{
p1=p1->lchild;
n[++top]=p1;
}
if(top>-1)
{
printf("%c",p1->a);
p1=n[top–];
p1=p1->rchild;
}
}
}