#include<stdio.h>
#include<malloc.h>
typedef struct tree{
struct tree * lchild;
struct tree * rchild;
char data;
}tree;
void qianxu(tree*t)
{
if(t)
{
printf("%c",t->data);
qianxu(t->lchild );
qianxu(t->rchild );
}
}
void zhongxu(tree * t)
{
if(t)
{
zhongxu(t->lchild);
printf("%c",t->data);
zhongxu(t->rchild);
}
}
void houxu(tree * t)
{
if(t)
{
houxu(t->lchild);
houxu(t->rchild);
printf("%c",t->data);
}
}
int count(tree *t)
{
int n;
if(t==NULL)
return 0;
else
n=1+count(t->lchild)+count(t->rchild);
return n;
}
tree * copy (tree *t)
{
tree * t1;
if(t==NULL)
t1=NULL;
else
{
t1=(tree *)malloc(sizeof(tree));
t1->data =t->data ;
t1->lchild =copy(t->lchild );
t1->rchild =copy(t->rchild );
}
return t1;
}
tree * createTree()
{
char ch;
tree * t;
scanf("%c",&ch);
getchar();
if(ch=='#')
{
return NULL;
}
else
{
t=(tree *)malloc(sizeof(tree));
t->data=ch;
printf("请输入%c的左子树的根结点:",ch);
t->lchild =createTree();
printf("请输入%c的右子树的根结点:",ch);
t->rchild =createTree();
return t;
}
}
int depth(tree *t)
{
int m,n;//m:左子树的深度,n:右子树的深度
if(t==NULL)
return 0;
else
{
m=depth(t->lchild );
n=depth(t->rchild );
if(m>n)
return m+1;
else
return n+1;
}
}
main()
{ tree * t;
tree *t1;
int n; //二叉树的结点总数
int d;//二叉树的深度
printf("空结点即用“#”表示\n");
printf("请输入二叉树的根结点:");
t=createTree();
printf("\n");
printf("该二叉树的前序遍历:");
qianxu(t);
printf("\n");
printf("该二叉树的中序遍历:");
zhongxu(t);
printf("\n");
printf("该二叉树的后序遍历:");
houxu(t);
printf("\n");
printf("该二叉树的结点总数是:");
n=count(t);
printf("%d",n);
printf("\n");
printf("该二叉树的深度是:");
d=depth(t);
printf("%d",n);
printf("\n");
printf("复制二叉树:");
t1=copy(t);
printf("新二叉树的后序遍历是:");
qianxu(t1);
printf("\n");
}