话不多说,直接上代码(在DEV C++等编译器上可通过)
#include<stdio.h>
#include<malloc.h>
#include<math.h>
typedef struct tree
{
int data;
struct tree* lchild;
struct tree* rchild;
} tree ,*bittree;
struct tree* creat() //创建二叉树
{
int data;
bittree t;
scanf("%d",&data);
if(data==0)
return 0;
else{
t=(bittree)malloc(sizeof(struct tree));
t->data=data;
printf("请输入%d的左子树",data);
t->lchild=creat();
printf("请输入%d的右子树",data);
t->rchild=creat();
return t;
}
}
void preorder(bittree t)//先序遍历
{
if(t==0){
return;
}
printf("%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
void inorder(bittree t)//中序遍历
{
if(t==0){
return;
}
inorder(t->lchild);
printf("%d",t->data);
inorder(t->rchild);
}
void lateorder(bittree t)//后序遍历
{
if(t==0){
return;
}
lateorder(t->lchild);
lateorder(t->rchild);
printf("%d",t->data);
}
//二叉树深度
int depth(bittree t){
int ldepth=0,rdepth=0;
if(t==0) return 0;
return fmax(depth(t->lchild),depth(t->rchild)+1);
}
//叶子节点数
int leafnode(bittree t)
{
int num1,num2;
if(t==0) return 0;
else if(t->lchild==0&&t->rchild==0)
return 1;
else{
num1=leafnode(t->lchild);
num2=leafnode(t->rchild);
return (num1+num2);
}
}
//结点数
int nodes(bittree t){
int node1,node2;
if(t==0) return 0;
else{
node1=nodes(t->lchild);
node2=nodes(t->rchild);
return(node1+node2+1);
}
}
// 交换左右子树
struct tree* swap(bittree t){
bittree temp;
if(t!=0){
swap(t->lchild);
swap(t->rchild);
temp=t->lchild;
t->lchild=t->rchild;
t->rchild=temp;
}
}
int main(){
bittree t,newtree;
int treedepth,numnode,leafnodes;
printf("请输入根节点的数据");
t=creat();
printf("先序遍历的结果如下\n");
preorder(t);
printf("\n中序遍历的结果如下\n");
inorder(t);
printf("\n后序遍历的结果如下\n");
lateorder(t);
printf("\n该二叉树的深度为\n");
treedepth=depth(t);
printf("%d",treedepth);
printf("\n该二叉树的结点个数为\n");
numnode=nodes(t);
printf("%d",numnode);
printf("\n该二叉树的叶子结点个数为\n");
leafnodes=leafnode(t);
printf("%d",leafnodes);
printf("\n下面进行左右两树的交换\n");
swap(t);
printf("\n新树先序遍历的结果如下\n");
preorder(t);
printf("\n新树中序遍历的结果如下\n");
inorder(t);
printf("\n新树后序遍历的结果如下\n");
lateorder(t);
}
注:此程序中是根据先序创建的,如下图,输入零表示无左子树或者右子树