#include<stdio.h>
#include<stdlib.h>
#define max 20//定义树的结点数
#define null 0
typedef struct btnode//定义二叉树结点类型
{
char date;//结点数据类型
struct btnode *lc,*rc;//左右指针
}bttree;
bttree *createtree(char *str,int i,int m)//将字符串str中第i到第m个字符创建树
{
bttree *p;
if(i>=m)
return null;
p=(bttree*)malloc(sizeof(bttree));//生成新结点
p->date=str[i];//将结点的第一个数据付给根
p->lc=createtree(str,2*i+1,m);//创建左子树
p->rc=createtree(str,2*i+2,m);//创建右子树
return (p);
}
bttree *jiaohuan(bttree *p)//将p指针指向的二叉树的左右子树进行互换。
{
bttree *stack[max];//指针类型的堆栈
int k;
k=0;
stack[k]=null;
if(p!=null)//交换p结点的左右孩子
{
k++;
stack[k]=p->lc;
p->lc=p->rc;
p->rc=stack[k];
p->lc=jiaohuan(p->lc);
p->rc=jiaohuan(p->rc);
}
return (p);
}
void xiangen(bttree *t)//先跟遍历
{
if(t!=null)
{
printf("%c",t->date);
if(t->lc)
{
printf("->");
xiangen(t->lc);
}
if(t->rc)
{
printf("->");
xiangen(t->rc);
}
}
}
void zhonggen(bttree *p)//中根遍历即中序遍历
{
if(p!=null)
{
zhonggen(p->lc);
printf("%c",p->date);
printf("->");
zhonggen(p->rc);
}
}
void hougen (bttree *p)//后根遍历
{
if(p!=null)
{
hougen(p->lc);
hougen(p->rc);
printf("%c",p->date);
printf("->");
}
}
void cengci(bttree *t,int m)//按层次遍历
{
bttree *queue[max];
bttree *p;
int front=0,rear=0,i;
queue[rear++]=t;
while(front!=rear)
{
p=queue[front];
front=(front+1)%m;
printf("%c->",p->date);//输出根结点
if(p->lc!=null)//遍历左子树
{
if((rear+1)%m!=front)
{
queue[rear]=p->lc;
rear=(rear+1)%m;
}
}
if(p->rc!=null)//遍历右子树
{
if((rear+1)%m!=front)
{
queue[rear]=p->rc;
rear=(rear+1)%m;
}
}
}
}
int main()
{
int i,n;
char str[max];
bttree *root;//二叉树根结点的指针
printf("请输入根结点数目n:");
scanf("%d",&n);
getchar();
printf("请输入%d个结点:",n);
for(i=0;i<n;i++)
str[i]=getchar();
printf("\n\n");
root=createtree(str,0,n);
printf("层次遍历是:\n");
cengci(root,n);
printf("\n先根遍历是:\n");
xiangen(root);
printf("\n中根遍历是:\n");
zhonggen(root);
printf("\n后根遍历是:\n");
hougen(root);
printf("\n\n");
root=jiaohuan(root);//交换左右子树
printf("左右子树交换后!\n");
printf("层次遍历是:\n");
cengci(root,n);
printf("\n先根遍历是:\n");
xiangen(root);
printf("\n中根遍历是:\n");
zhonggen(root);
printf("\n后根遍历是:\n");
hougen(root);
printf("\n\n");
system("pause");
}