数据结构实验之二叉树的建立与遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
3
5
Hint
Source
ma6174
解题思路:许多二叉树的基本操作混合在一起,理解起来也比较容易。输出:先序、中序、后序,都可以用递归解决,如果是层序遍历则需要用到队列。深度和叶子数,也是可以用递归求解。
AC代码:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef int elem;
int flag;
typedef struct node
{
elem date;
struct node *lchild;
struct node *rchild;
}BiTree;
BiTree *createTree(int a, BiTree *root)
{
if(!root)
{
root = (BiTree *)malloc(sizeof(BiTree));
root->date = a;
root->lchild = root->rchild = NULL;
}
else
{
if(a < root->date)
{
root->lchild = createTree(a, root->lchild);
}
else
{
root->rchild = createTree(a, root->rchild);
}
}
return root;
}
void mid_treverse(BiTree *root)
{
if(root != NULL)
{
mid_treverse(root->lchild);
if(flag == 0)
{
printf("%d",root->date);
flag = 1;
}
else
{
printf(" %d",root->date);
}
mid_treverse(root->rchild);
}
}
int main()
{
int n;
int a;
BiTree *root;
while(~scanf("%d", &n))
{
flag = 0;
root = NULL;
int i;
for(i = 0; i < n; i++)
{
scanf("%d", &a);
root = createTree(a,root);
}
mid_treverse(root);
printf("\n");
}
return 0;
}