您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树的建立与遍历

2017-05-26 19:50 357 查看

数据结构实验之二叉树的建立与遍历

Time Limit: 1000MS Memory Limit: 65536KB
[align=center]Submit Statistic Discuss[/align]

Problem Description

       已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。

Input

 输入一个长度小于50个字符的字符串。

Output

输出共有4行:

第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。

Example Input

abc,,de,g,,f,,,


Example Output

cbegdfacgefdba35


#include<stdio.h>
using namespace std;
char ch[60],*p;
struct node
{
char data;
node *lt,*rt;
};

node *creat(char *&xx)
{
if(*xx=='\0')
return NULL;
if(*xx==',')
{
xx++;
return NULL;
}
node *r=new node;
r->data=*xx++;
r->lt=creat(xx);
r->rt=creat(xx);
return r;
}
void mout(node *r)
{
if(r==NULL)
return ;
mout(r->lt);
printf("%c",r->data);
mout(r->rt);
}

void hout(node *r)
{
if(r==NULL)
return ;
hout(r->lt);
hout(r->rt);
printf("%c",r->data);
}
int yezi(node *root,int &k)
{
if(root)
{
if(root->lt==NULL&&root->rt==NULL)
k++;
yezi(root->lt,k);
yezi(root->rt,k);
}
return k;

}
int depth(node *root)
{
int deep=0;
if(root)
{
int l=depth(root->lt);
int r=depth(root->rt);
deep=l>=r?l+1:r+1;
}
return deep;
}
int main()
{
node *root;
scanf("%s",ch);
p=ch;
root=creat(p);
mout(root);
printf("\n");
hout(root);
printf("\n");
int k=0;
printf("%d\n",yezi(root,k));

printf("%d\n",depth(root));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: