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

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

2017-08-07 17:04 447 查看


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

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic


Problem Description

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


Input

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


Output

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


Example Input

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



Example Output

abcdefg
xnuli



Hint

 


Author

 xam

AC:

1、队列做法

#include <bits/stdc++.h>

using namespace std;

struct Btree
{
char data;
struct Btree *lc,*rc;
};

char st[10010];
int ans;

struct Btree* creat()
{
struct Btree *root;
if(st[++ans] == ',')
{
root = NULL;
}
else
{
root = new Btree;
root -> data = st[ans];
root -> lc = creat();
root -> rc = creat();
}
return root;
};

void cengxu(struct Btree * root)
{
queue<Btree*>q;
if(root)
q.push(root);
Btree *qq;
while(!q.empty())
{
qq = q.front();
q.pop();
if(qq -> lc)
q.push(qq->lc);
if(qq -> rc)
q.push(qq->rc);
cout<<qq -> data;
}
}

int main()
{
int t;
while(cin>>t)
{
while(t--)
{
cin>>st;
ans = -1;
struct Btree *root;
root = creat();
cengxu(root);
cout<<endl;
}
}
return 0;
}


2、数组模拟队列

#include <iostream>
#include<cstdio>
#include<cstring>

using namespace std;

struct node
{
char data;
struct node *lc, *rc;
};

char st[1000];
int cnt;

struct node *creat()
{
struct node *root;
if(st[++cnt] == ',')
root = NULL;
else
{
root = new node;
root -> data = st[cnt];
root -> lc = creat();
root -> rc = creat();
}
return root;
}

void cengci(struct node * root)
{
struct node *temp[1000];//关键中间变量存放每一层的数据 ,做队列处理
int in = 0, out = 0;
temp[in++] = root; //每次把这一层存入,然后输出的时候就把他的左右孩子存入 ,做队列处理
while(in > out)//结束条件为队列空或者不再有孩子
{
if(temp[out])//节点不存在||为空时跳过
{
printf("%c", temp[out] -> data);//例如一颗完全二叉树abcdefg  输出a的时候把bc放入,输出b的时候把b
temp[in++] = temp[out] -> lc;//的孩子放入也就是de,再输出c并且放入孩子fg,依次这样,达到层序的要求
temp[in++] = temp[out] -> rc;
}
out++;//下一节点
}
}

int main()
{
struct node*root;
int t;
cin>>t;
while(t--)
{
cin>>st;
cnt = -1;
root = creat();
cengci(root);
cout<<endl;
}
return 0;
}

/***************************************************
User name:
Result: Accepted
Take time: 0ms
Take Memory: 168KB
Submit time: 2017-02-10 15:56:37
****************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息