数据结构实验之二叉树五:层序遍历
Problem Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample Input
2
abd,eg,cf,
xnl,i,u,
Sample Output
abcdefg
xnuli
不知道为什么这样老错
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
#include <queue>
using namespace std;
int top,sum,t;
char a[55],b[55],n;
typedef struct treenode
{
char data;
treenode *l,*r;
}Node;
Node *creat2()
{
Node *root;
if(a[++top]==',') root=NULL;
else
{
root=(Node *)malloc(sizeof(Node));
root->data=a[top];
root->l=creat2();
root->r=creat2();
}
return root;
}
void cengxu(Node *root)
{
queue<Node *> q;
q.push(root);
while(!q.empty())
{
root=q.front();
printf("%c",root->data);
q.pop();
if(root->l) q.push(root->l);
if(root->r) q.push(root->r);
}
}
int deep(Node *root)
{
if(!root) return 0;
int l=deep(root->l)+1;
int r=deep(root->r)+1;
return max(l,r);
}
int main()
{
Node *root;
scanf("%d",&t);
while(t--)
{
top=-1;
scanf("%s",a);
root=creat2();
cengxu(root);
printf("\n");
}
return 0;
}
这样就对了。。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
#include <queue>
using namespace std;
int top,sum,t;
char a[55],b[55],n;
typedef struct treenode
{
char data;
treenode *l,*r;
}Node;
Node *creat2()
{
Node *root;
if(a[++top]==',') root=NULL;
else
{
root=(Node *)malloc(sizeof(Node));
root->data=a[top];
root->l=creat2();
root->r=creat2();
}
return root;
}
void cengxu(Node *root)
{
queue<Node *> q;
if(root) {printf("%c",root->data);q.push(root);}
while(!q.empty())
{
root=q.front();
q.pop();
if(root->l) {printf("%c",root->l->data);q.push(root->l);}
if(root->r) {printf("%c",root->r->data);q.push(root->r);}
}
}
int deep(Node *root)
{
if(!root) return 0;
int l=deep(root->l)+1;
int r=deep(root->r)+1;
return max(l,r);
}
int main()
{
Node *root;
scanf("%d",&t);
while(t--)
{
top=-1;
scanf("%s",a);
root=creat2();
cengxu(root);
printf("\n");
}
return 0;
}