刚开始接触树,在这里总结一下二叉树的基础操作。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct tree
{
char data;
struct tree *l,*r;
};
char a[100];
int i=0;
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
struct tree * creat() **//先序建树**
{
struct tree *root;
if(a[i]==',')
{
i++;
return NULL;
}
else
{
root=(struct tree *)malloc(sizeof(struct tree ));
root->data=a[i++];
root->l=creat();
root->r=creat();
}
return root;
};
void mid(struct tree *root) **//中序遍历**
{
if(root==NULL)
return ;
else
{
mid(root->l);
printf("%c",root->data);
mid(root->r);
}
}
void aft(struct tree *root) **//后序遍历**
{
if(root==NULL)
return ;
else
{
aft(root->l);
aft(root->r);
printf("%c",root->data);
}
}
int le(struct tree *root) **//统计叶子数**
{
struct tree *a[100];
int n,m,flag;
n=m=flag=0;
a[n++]=root;
while(n>m)
{
if(a[m])
{
if(a[m]->l==NULL&&a[m]->r==NULL)
flag++;
a[n++]=a[m]->l;
a[n++]=a[m]->r;
}
m++;
}
return flag;
}
int dep(struct tree *root) **//计算树的深度**
{
int dl,dr,dp;
if(root==NULL)
return 0;
else
{
dl=dep(root->l);
dr=dep(root->r);
dp=max(dl,dr)+1;
}
return dp;
}
int main()
{
struct tree *root;
scanf("%s",a);
root=creat();
mid(root);
printf("\n");
aft(root);
printf("\n");
printf("%d\n",le(root));
printf("%d\n",dep(root));
return 0;
}