明明PE,显示WA,郁闷。
层次遍历,利用队列,把根入队列
循环-》输出队首-》儿子入队列
over
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef struct node
{
int val;
struct node *left;
struct node *right;
void setVal(int v)
{
this->val = v;
left = right = NULL;
}
}Tree;
void createTree(Tree tree[],int n)
{
int val,childIndex;
for(int i=0;i<n;++i)
{
scanf("%d",&val);
tree[i].setVal(val);
}
for(int i=0;i<n;++i)
{
char ch[2];
scanf("%s",ch);
if(ch[0] == 'd')
{
scanf("%d",&childIndex);
tree[i].left = &tree[childIndex-1];
scanf("%d",&childIndex);
tree[i].right = &tree[childIndex-1];
}
else if(ch[0] == 'l')
{
scanf("%d",&childIndex);
tree[i].left = &tree[childIndex-1];
}
else if(ch[0] == 'r')
{
scanf("%d",&childIndex);
tree[i].right = &tree[childIndex-1];
}
}
}
void printTree(Tree *tree)
{
queue<Tree *>qu;
qu.push(tree);
bool first = true;
while(!qu.empty())
{
Tree *t = qu.front();
qu.pop();
if(first)
printf("%d",t->val);
else
printf(" %d",t->val);
first = false;
if(t->left != NULL)
{
qu.push(t->left);
}
if(t->right != NULL)
{
qu.push(t->right);
}
}
}
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
Tree tree[1111];
createTree(tree,n);
printTree(tree);
}
return 0;
}