数据结构实验之二叉树的建立与遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
3
5
Hint
Source
ma6174
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char pre[55];
int l;
struct node
{
char data;
struct node *left;
struct node *right;
};
struct node *creat()
{
char p;
struct node *root;
p = pre[l++];
if(p == ',')
return NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root -> data = p;
root -> left = creat();
root -> right = creat();
}
return root;
};
void mid(struct node *root)
{
if(root)
{
mid(root -> left);
printf("%c", root -> data);
mid(root -> right);
}
}
void post(struct node *root)
{
if(root)
{
post(root -> left);
post(root -> right);
printf("%c", root -> data);
}
}
int leave(struct node *root)
{
if(root == NULL)
return 0;
if(root -> left == NULL && root -> right == NULL)
return 1;
else
return leave(root -> left) + leave(root -> right);
}
int height(struct node *root)
{
if(root)
{
int n = height(root -> left);
int m = height(root -> right);
return (m > n)?(m + 1):(n + 1);
}
return 0;
}
int main()
{
int h, num;
scanf("%s", pre);
struct node *root;
root = creat();
mid(root);
printf("\n");
post(root);
printf("\n");
num = leave(root);
printf("%d\n", num);
h = height(root);
printf("%d\n", h);
return 0;
}