二叉树的建立及遍历算法的实现

#include
#include
#define max 100

typedef struct node{ //二叉树结构
char data;
struct node *lc,*rc; //左右子树
}bt,*list;
/*
二叉树
A
/ \
B C
/ \ \
D E F
/ / \
K G H

input
ABDK000E00C0FG00H00
chen000j00i0ha00o00
ouput
ABDKECFGH
KDBEACGFH
KDEBGHFCA
*/

int creat(list*root){ //创建一棵二叉树,root使用的是二维指针
char n;
scanf(" %c",&n); //注%C前面加空格是为了起间隔作用 scanf不读入空格
if (n=='0') //0为间隔
{
*root=NULL; return 0; //输入结束
}
*root=(list)malloc(sizeof(bt));
if (!*root) return 0;
(*root)->data=n;
creat(&(*root)->lc);
creat(&(*root)->rc);
return 1;
}

int pre(list root){ //先序遍历
if (!root) return 0;
printf("%c",root->data);
pre(root->lc);
pre(root->rc);
return 1;
}
int mid(list root){ //中序遍历
if (!root) return 0;
mid(root->lc);
printf("%c",root->data);
mid(root->rc);
return 1;
}

int bh(list root){ //后序遍历
if (!root) return 0;
bh(root->lc);
bh(root->rc);
printf("%c",root->data);
return 1;
}
int sum(list root,int *cnt){ //求结点的个数sum
if(root){
(*cnt)++;
sum(root->lc,cnt);
sum(root->rc,cnt);
return 1;
}
return 0;
}
int sumleaf(list root,int *cnt){ //求叶子节点的个数
if (root)
{
if ((!root->lc)&&(!root->rc))
{ (*cnt)++; }
sumleaf(root->lc,cnt);
sumleaf(root->rc,cnt);
return 1;
}
return 0;
}
int deep(list root,int *cnt){ //求深度
if (!root)
{
*cnt=0; return 0;
}
int m,n;
n=m=*cnt;
deep(root->lc,&m);
deep(root->rc,&n);
*cnt=m+1;
if(mreturn 1;
}

void main()
{system("color F0");
list b,s,m;
int n,t=1;
char ch='\0';
printf("***********Bitree************\n");
while(t){ //循环操作
printf("输入一个二叉树:\n");
s=m=b=NULL; //二叉树的初始化
creat(&b);
//按三种遍历输出二叉树
printf("\n前序遍历为:"); pre(b);
printf("\n中序遍历为:"); mid(b);
printf("\n后序遍历为:"); bh(b); printf("\n");
//求节点数目,叶子节点的个数,深度
n=0; sum(b,&n); printf("节点数目为: %d\n",n);
n=0; sumleaf(b,&n); printf("叶子节点的个数为: %d\n",n);
n=0; deep(b,&n); printf("树的深度为: %d\n",n);
//二叉树的复制

//继续则输入 1,退出输入 0
printf("继续输入请按1,退出请按0:\n");
scanf("%d",&t);
}
}

相关文档
最新文档