数据结构实验之二叉树的建立与遍历
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
char a[51],i;
typedef struct tree
{
char data;
tree *l,*r;
}tree;
tree*create()
{
tree*t;
if(a[++i] == ',')
t=NULL;
else
{
t=new tree;
t->data=a[i];
t->l=create();
t->r=create();
}
return t;
}
void zhongxu(tree*t)
{
if(t)
{
zhongxu(t->l);
cout<<t->data;
zhongxu(t->r);
}
}
void houxu(tree*t)
{
if(t)
{
houxu(t->l);
houxu(t->r);
cout<<t->data;
}
}
int leave(tree*t)
{
if(t == NULL)
return 0;
if(t->l == NULL&&t->r == NULL)
return 1;
else
return leave(t->l)+leave(t->r);
}
int depth(tree*t)
{
int d=0;
if(t)
{
int l1=depth(t->l)+1;
int l2=depth(t->r)+1;
if(l1<l2)
d=l2;
else
d=l1;
}
return d;
}
int main()
{
cin>>a;
tree *t;
i=-1;
t=create();
zhongxu(t);
cout<<endl;
houxu(t);
cout<<endl;
int l=leave(t);
int d=depth(t);
cout<<l<<endl<<d<<endl;
return 0;
}