数据结构实验之二叉树五:层序遍历
来源:互联网 发布:开农村淘宝靠什么赚钱 编辑:程序博客网 时间:2024/06/12 21:14
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Example Input
2abd,,eg,,,cf,,,xnl,,i,,u,,
Example Output
abcdefgxnuli
代码:
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
int cnt, k, n;
char a[51], b[51];
struct node
{
char data;
struct node *l, *r;
};
struct node *create()
{
struct node *root;
root=(struct node*)malloc(sizeof(struct node));
if(a[++cnt]==',')
root = NULL;
else
{
if(a[cnt])
{
root->data = a[cnt];
root->l = create();
root->r = create();
}
}
return root;
}
void shuchu(struct node *root) //用一个结构体数组,保存输出结点,每输出一个结点就把该结点的左孩子和右孩子保存在数组的最后。
{
int in=0, out=0;
struct node *a[100];
a[in++] = root;
while(in>out)
{
if(a[out])
{
cout << a[out]->data;
a[in++]=a[out]->l;
a[in++]=a[out]->r;
}
out++;
}
}
int main()
{
int t;
while(~scanf("%d", &t))
{
while(t--)
{
scanf("%s", a);
struct node *root;
cnt = -1;
root = create();
shuchu(root);
cout << endl;
}
}
return 0;
}
#include <string.h>
using namespace std;
int cnt, k, n;
char a[51], b[51];
struct node
{
char data;
struct node *l, *r;
};
struct node *create()
{
struct node *root;
root=(struct node*)malloc(sizeof(struct node));
if(a[++cnt]==',')
root = NULL;
else
{
if(a[cnt])
{
root->data = a[cnt];
root->l = create();
root->r = create();
}
}
return root;
}
void shuchu(struct node *root) //用一个结构体数组,保存输出结点,每输出一个结点就把该结点的左孩子和右孩子保存在数组的最后。
{
int in=0, out=0;
struct node *a[100];
a[in++] = root;
while(in>out)
{
if(a[out])
{
cout << a[out]->data;
a[in++]=a[out]->l;
a[in++]=a[out]->r;
}
out++;
}
}
int main()
{
int t;
while(~scanf("%d", &t))
{
while(t--)
{
scanf("%s", a);
struct node *root;
cnt = -1;
root = create();
shuchu(root);
cout << endl;
}
}
return 0;
}
阅读全文
0 0
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 设计模式学习(四) — 行为模式
- 第007讲-第011讲 从1000个代码案例中学习人工智能和大数据实战
- 五年开发经验
- 模块化数据和模版填充页面,并且用本地存储来提高用户体验。
- 自己考试用的!!!!
- 数据结构实验之二叉树五:层序遍历
- SQL查询语句中select from where group by having order by的执行顺序
- scrapy爬虫框架的详细用法
- eclipse快捷键以及多行注释
- 使用TensorFlow进行特征提取(中层特征)以及mat文件转为tfrecord方法
- 【51nod】1073 约瑟夫环
- 插件webuploader实现文件上传
- 上班太远,换开发技术换工作,值得吗?
- 删除数据库所有存储过程的SQL语句