Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample
Input
2
abd,,eg,,,cf,,,
xnl,,i,,u,,
Output
abcdefg
xnuli
Hint
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
char data;
struct node *l, *r;
} Tree;
char pre[55];
int cnt;
Tree *creat()
{
Tree *root;
if(pre[cnt] == ',')
{
cnt++;
root = NULL;
}
else
{
root = new Tree;
root->data = pre[cnt++];
root->l = creat();
root->r = creat();
}
return root;
}
void cengxu(Tree *root)//模拟队列实现层序遍历
{
Tree *que[10000];
int i, j;
i = 0, j = 0;
que[i++] = root;
while(i > j)
{
if(que[j])
{
printf("%c", que[j]->data);
que[i++] = que[j]->l;
que[i++] = que[j]->r;
}
j++;
}
}
/*void cengxu(Tree *root)//用STL中的queue队列实现
{
Tree* temp;
queue<Tree *>q;
q.push(root);//首先根节点入队
//将根节点压入队列,每次再从队列中取出队首
//每次先输出取出的节点的值,再将该节点的左右节点压入队列(有的话)
while(!q.empty())
{
temp = q.front();
q.pop();
if(temp)
{
printf("%c", temp->data);
if(temp->l)
q.push(temp->l);
if(temp->r)
q.push(temp->r);
}
}
}*/
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
cnt = 0;
scanf("%s", pre);
Tree *root = creat();
cengxu(root);
printf("\n");
}
return 0;
}