http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=3344
数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
输出
输出二叉树的层次遍历序列。
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
using namespace std;
typedef char type;
typedef struct tnode
{
type data;
tnode *lc;
tnode *rc;
}tnode,*tree;
int i=0;
type s[60];
tree creat(tree &T)
{
if(s[i]==',')
{
T=NULL;
i++;
}
else
{
T=(tree)malloc(sizeof(tnode));
T->data=s[i];
i++;
T->lc=creat(T->lc);
T->rc=creat(T->rc);
}
return T;
}
void cengci(tree T)
{
queue<tree>S;
if(T)
{
cout<<T->data;
S.push(T);
}
while(!S.empty())
{
T= S.front();
S.pop();
if(T->lc)
{
printf("%c",T->lc->data);
S.push(T->lc);
}
if(T->rc)
{
printf("%c",T->rc->data);
S.push(T->rc);
}
}
}
int main()
{
tree T;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
i=0;
T=creat(T);
cengci(T);
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
using namespace std;
typedef char type;
typedef struct tnode
{
type data;
tnode *lc;
tnode *rc;
}tnode,*tree;
int i=0;
type s[60];
tree creat(tree &T)
{
if(s[i]==',')
{
T=NULL;
i++;
}
else
{
T=(tree)malloc(sizeof(tnode));
T->data=s[i];
i++;
T->lc=creat(T->lc);
T->rc=creat(T->rc);
}
return T;
}
void cengci(tree T)
{
queue<tree>S;
if(T)
{
cout<<T->data;
S.push(T);
}
while(!S.empty())
{
T= S.front();
S.pop();
if(T->lc)
{
printf("%c",T->lc->data);
S.push(T->lc);
}
if(T->rc)
{
printf("%c",T->rc->data);
S.push(T->rc);
}
}
}
int main()
{
tree T;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
i=0;
T=creat(T);
cengci(T);
printf("\n");
}
return 0;
}