您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树五:层序遍历

2016-08-08 20:49 375 查看


数据结构实验之二叉树五:层序遍历


Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。

输入

 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。

输出

 输出二叉树的层次遍历序列。

示例输入

2
abd,,eg,,,cf,,,
xnl,,i,,u,,


示例输出

abcdefg
xnuli


提示

 

来源

 xam

注意使用队列实现树的深度遍历。

#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
struct node
{
char data;
struct node *left;
struct node *right;
};
int i;
char a[100000];
struct node* create(struct node* root)      //建立二叉树,定义一个字符变量ch,然后每次只输入一个字符。
{
char ch;
ch=a[i++];
if(ch!=',')
{
root=new node();
root->data=ch;
root->left= create(root->left);
root->right=create(root->right);
}
else
{
root=NULL;
}
return root;
};
void cengci(struct node *root)
{
queue<node*>q;        //注意队列容器的数据类型,是结构体的指针型
q.push(root);
struct node *temp=new node;
while(!q.empty())
{
temp=q.front();
q.pop();
if(temp)
{
cout<<temp->data;
q.push(temp->left);
q.push(temp->right);
}
}

}
int main()
{
int n;

cin>>n;
while(n--)
{
struct node *root=new node();           //注意这种定义结点的方法
cin>>a;
i=0;
root=create(root);
cengci(root);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: