Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
Output
Example Input
2 abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
abcdefg xnuli
Hint
Author
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct binode
{
char data;
struct binode *lchild;
struct binode *rchild;
}binode, *bitree;
char a[55];
int i;
bitree creat(bitree &T)
{
if(a[i++] == ',')
T = NULL;
else
{
T = new binode;
T->data = a[i - 1];
T->lchild = creat(T->lchild);
T->rchild = creat(T->rchild);
}
return T;
}
void browse(bitree T)
{
int i = 0;
int j = 0;
bitree a[55];
a[i++] = T;
while(i > j)
{
if(a[j])
{
cout<<a[j]->data;
if(a[j]->lchild)
a[i++] = a[j]->lchild;
if(a[j]->rchild)
a[i++] = a[j]->rchild;
}
j++;
}
}
int main()
{
int n;
cin>>n;
while(n--)
{
bitree T;
i = 0;
cin>>a;
T = creat(T);
browse(T);
cout<<endl;
}
return 0;
}