Description
已知二叉树的一个按前序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树,并输出建立二叉树的前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数。
Input
多组测试数据,对于每组测试数据,输入一个长度小于50的按前序遍历输入的字符序列。
Output
对于每组测试数据,第1行输出其前序遍历序列、第2行输出其中序遍历序列、第3行输出其后序遍历序列、第4行输出其深度、第5行输出其叶子数。
Sample
Input
abc,,de,g,,f,,,
Output
abcdegf
cbegdfa
cgefdba
abcdefg
5
3
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
const int N = 1e5 + 10;
using namespace std;
struct tree //定义树的结构体类型
{
char data;
tree *l,*r;
};
int cnt; //记录根结点的位置
string s; //输入的字符串
tree *buildtree(tree *root) //建树
{
if(s[cnt]==',')
{
root=NULL;
cnt++;
}
else
{
root=new tree;
root->data=s[cnt++];
root->l=buildtree(root->l); //建立左子树
root->r=buildtree(root->r); //建立右子树
}
return root;
}
void preorder(tree *root) //前(根)序遍历:前->左->右
{
if(root)
{
printf("%c",root->data);
preorder(root->l);
preorder(root->r);
}
}
void midorder(tree *root) //中(根)序遍历:左->前->右
{
if(root)
{
midorder(root->l);
printf("%c",root->data);
midorder(root->r);
}
}
void postorder(tree *root) //后(根)序遍历:左->右->前
{
if(root)
{
postorder(root->l);
postorder(root->r);
printf("%c",root->data);
}
}
void cengxu(tree *root) //指针数组实现层序遍历
{
if(!root)
return ;
tree *tr[111]; //创建tree指针类型的指针数组
tree *p;
tr[1]=root; //先保存二叉树根节点
int l,r;
l=1;
r=1;
while(l<=r)
{
p=tr[l++];
if(p!=NULL)
printf("%c",p->data);
if(p->l!=NULL)
tr[++r]=p->l;
if(p->r!=NULL)
tr[++r]=p->r;
}
}
int depth(tree *root) //求树的深度
{
int ans=0;
int ld;
int rd;
if(!root)
ans=0;
else
{
ld=depth(root->l);
rd=depth(root->r);
ans=max(ld,rd)+1;
}
return ans;
}
int leaves(tree *root) //求叶子结点的数量
{
int ans=0;
if(root)
{
if(root->l==NULL&&root->r==NULL)
{
ans++;
}
else
{
if(root->l!=NULL)
ans+=leaves(root->l);
if(root->r!=NULL)
ans+=leaves(root->r);
}
}
return ans;
}
int main()
{
while(cin>>s)
{
cnt=0;
tree *root=new tree;
root=buildtree(root); //建树
preorder(root); //前序遍历
cout<<endl;
midorder(root); //中序遍历
cout<<endl;
postorder(root); //后序遍历
cout<<endl;
cengxu(root); //层序遍历
cout<<endl;
cout<<depth(root)<<endl; //树的深度
cout<<leaves(root)<<endl; //树的叶子数量
}
return 0;
}