数据结构实验之二叉树的建立与遍历
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
cbegdfacgefdba35
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char num;
struct node *l,*r;
};
int flog,m,n;
char i[1000];
struct node* kk(int a)
{
struct node *root;
if(i[++flog]==',')
return NULL;
else
{
int p=a;
a++;
root=(struct node *)malloc(sizeof(struct node));
root->num=i[flog];
root->l=kk(a);
root->r=kk(a);
if(root->l==NULL&&root->r==NULL)
m++;
if(root->l==NULL&&root->r==NULL)
{
if(n<p)
n=p;
}
}
return root;
}
void gg(struct node *root)
{
if(root==NULL)
return ;
gg(root->l);
printf("%c",root->num);
gg(root->r);
}
void zz(struct node *root)
{
if(root==NULL)
return ;
zz(root->l);
zz(root->r);
printf("%c",root->num);
}
int main()
{
int a=1;
struct node *root;
scanf("%s",i);
flog=-1;
root=kk(a);
gg(root);
printf("\n");
zz(root);
printf("\n");
printf("%d\n%d\n",m,n);
return 0;
}