Time Limit: 1000MS
Memory Limit: 65536KB
Submit
Statistic
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数
t (t<1000)
,代表有
t
行测试数据。每行是一个长度小于
50
个字符的字符串。
Output
输出二叉树的层次遍历序列。
Example Input
2
abd,,eg,,,cf,,,
xnl,,i,,u,,
Example Output
abcdefg
xnuli
#include <iostream>
#include <stdio.h>
char str[123456];
int g=0,t=0;
using namespace std;
typedef struct BitTree
{
int data;
BitTree *rchild,*lchild;
}Tree;
Tree *creat(Tree *p)
{
char c;
c = str[g++];
if(c==','||c=='\0')
{
return NULL;
}
else
{
p = new Tree;
p->data = c;
p->lchild = creat(p->lchild);
p->rchild = creat(p->rchild);
}
return p;
}
void sequence(Tree *root)
{
int out=0,in=0;
BitTree *q[100];
q[in++] = root;
while(in>out)
{
if(q[out])
{
printf("%c",q[out]->data);
q[in++] = q[out]->lchild;
q[in++] = q[out]->rchild;
}
out++;
}
}
int main()
{
int N;
scanf("%d",&N);
while(N--)
{ scanf("%s",str);
g=0;
Tree *root;
root = creat(root);
sequence(root);
printf("\n");
}
return 0;
}
转载于:https://www.cnblogs.com/CCCrunner/p/6444588.html
相关资源:JAVA上百实例源码以及开源项目