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>
using namespace std;
char pre[55];
int cnt=0;
typedef struct node
{
char data;
node *l,*r;
}Tree;
//根据先序遍历建树
Tree* buildtree()
{
Tree *root;
if(pre[cnt]==',')
{
root = NULL;
cnt++;
}
else
{
root = new Tree;
root->data=pre[cnt++];
root->l=buildtree();
root->r=buildtree();
}
return root;
}
//先序遍历
void fro(Tree *root)
{
if(root)
{
cout<<root->data;
fro(root->l);
fro(root->r);
}
}
//中序遍历
void mid(Tree *root)
{
if(root)
{
mid(root->l);
cout<<root->data;
mid(root->r);
}
}
//后序遍历
void post(Tree *root)
{
if(root)
{
post(root->l);
post(root->r);
cout<<root->data;
}
}
//层序遍历
void Cengxu(Tree *root)
{
queue<Tree *> t;
t.push(root);
while(!t.empty())
{
root=t.front();
t.pop();
if(root)
{
cout<<root->data;
t.push(root->l);
t.push(root->r);
}
}
}
//深度
int Deep_Tree(Tree *root)
{
int sum=0,dl,dr;
if(root)
{
dl=Deep_Tree(root->l);
dr=Deep_Tree(root->r);
sum=1+(dl > dr ? dl:dr);
}
return sum;
}
//叶子数目
int leave_Tree(Tree *root)
{
if(!root)
return 0;
if(!root->l&&!root->r)
return 1;
else
return leave_Tree(root->l)+leave_Tree(root->r);
}
int main()
{
ios::sync_with_stdio(false);
Tree *root;
while(cin>>pre)
{
cnt=0;
root=buildtree();
fro(root);
cout<<endl;
mid(root);
cout<<endl;
post(root);
cout<<endl;
Cengxu(root);
cout<<endl;
cout<<Deep_Tree(root)<<endl;
cout<<leave_Tree(root)<<endl;
}
return 0;
}