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;
typedef struct node
{
int data;
struct node*left;
struct node*right;
}tree;
char str[55];
int flag=0;
tree*creat(tree*root)
{
if(str[flag]==',')
{
flag++;
return NULL;
}
else
{
root=(tree*)malloc(sizeof(tree));
root->data=str[flag++];
root->left=creat(root->left);
root->right=creat(root->right);
}
return root;
}
void first(tree*root)
{
if(root!=NULL)
{
printf("%c",root->data);
first(root->left);
first(root->right);
}
}
void mid(tree*root)
{
if(root!=NULL)
{
mid(root->left);
printf("%c",root->data);
mid(root->right);
}
}
void last(tree*root)
{
if(root!=NULL)
{
last(root->left);
last(root->right);
printf("%c",root->data);
}
}
void levelOrder(tree*root)
{
tree*p[55];
int in,out;
in=out=0;
p[in++]=root;
while(in>out)
{
if(p[out])
{
printf("%c",p[out]->data);
p[in++]=p[out]->left;
p[in++]=p[out]->right;
}
out++;
}
}
int deep(tree*root)
{
if(root==NULL)
{
return 0;
}
else
{
return max(deep(root->left)+1,deep(root->right)+1);
}
}
int coutlevel(tree*root)
{
if(root==NULL)
{
return 0;
}
if(root->left==NULL&&root->right==NULL)
{
return 1;
}
return coutlevel(root->left)+coutlevel(root->right);
}
int main()
{
tree*root;
while(~scanf("%s",str))
{
flag=0;
root=creat(root);
first(root);
printf("\n");
mid(root);
printf("\n");
last(root);
printf("\n");
levelOrder(root);
printf("\n");
printf("%d\n",deep(root));
printf("%d\n",coutlevel(root));
}
return 0;
}