二叉树day1
代码:
- 二叉树的创建
- 二叉树的前序遍历 中序遍历 后序遍历 层序遍历
- 二叉树叶子结点和深度的计算
#include <stdio.h>
#include <stdlib.h>
char s[55];
int i, len, num, sum;
struct tree
{
char data;
struct tree *Lchild;
struct tree *Rchild;
};
struct tree * creat()
{
struct tree *root;
if(s[++i]!=',')
{
root = (struct tree *)malloc(sizeof(struct tree));
root -> data = s[i];
root -> Lchild = creat();
root -> Rchild = creat();
if(root -> Rchild==NULL&&root -> Lchild==NULL)//判断叶子节点数
{
num++;
}
}else
{
root = NULL;
}
return root;
}
void inshow(struct tree *t)//中序遍历
{
if(t!=NULL)
{
inshow(t->Lchild);
printf("%c", t->data);
inshow(t->Rchild);
}
}
void postshow(struct tree *t)//后序遍历
{
if(t!=NULL)
{
postshow(t->Lchild);
postshow(t->Rchild);
printf("%c", t->data);
}
}
void show(struct tree *t)//前序遍历
{
if(t!=NULL)
{
show(t->Lchild);
show(t->Rchild);
printf("%c", t->data);
}
}
int depth(struct tree *t)
{
int l, r;
if(t==NULL)
{
return 0;
}
else
{
l = depth(t->Lchild);
r = depth(t->Rchild);
return l>r?l+1:r+1;
}
}
void levelshow(struct tree *head)
{
struct tree *temp[150];
int front=0, rear=0;
temp[rear++] = head;
while(front<rear)
{
if(temp[front])
{
printf("%c", temp[front]->data);
temp[rear++] = temp[front]->Lchild;
temp[rear++] = temp[front]->Rchild;
}
front++;
}
}
int main()
{
int n;
scanf("%d", &n);
getchar();
while(n--)
{
gets(s);
len = strlen(s);
struct tree *head;
i = -1, num = 0;
head = creat();
inshow(head);//中序遍历
printf("\n");
postshow(head);//后序遍历
printf("\n");
show(head); //前序遍历
printf("\n");
levelshow(head);//层序遍历
printf("\n");
printf("%d\n", num);//叶子结点数
printf("%d\n", depth(head));//深度
}
return 0;
}