您的位置:首页 > 其它

*浙大PAT甲级 1099层次遍历二叉查找树

2016-09-07 16:00 337 查看
先通过输入进行建树,然后根据中序遍历对应从小到大的数,再进行bfs进行层次遍历。

AC代码:

#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
#include<hash_map>
#define ll long long
#define inf 24*60*60
using namespace std;
struct node
{
int l=-1;
int r=-1;
int data;
};
node a[105];
int num[105];
int shu=0;
void f(int x)
{
if(x==-1)
return;
f(a[x].l);
num[shu++]=x;
f(a[x].r);
}
void bfs(int x)
{
queue<node> q;
q.push(a[x]);
printf("%d",a[x].data);
while(!q.empty())
{
node tmp=q.front();
q.pop();
if(tmp.l!=-1)
{
printf(" %d",a[tmp.l].data);
q.push(a[tmp.l]);
}
if(tmp.r!=-1)
{
printf(" %d",a[tmp.r].data);
q.push(a[tmp.r]);
}
}
}
int b[105];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d %d",&a[i].l,&a[i].r);
}
for(int i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
sort(b,b+n);
f(0);
for(int i=0;i<n;i++)
{
a[num[i]].data=b[i];
}
bfs(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: