PTA L2-011 玩转二叉树 二叉树+bfs

时间:2023-03-10 01:14:12
PTA L2-011 玩转二叉树 二叉树+bfs

思路:

先建树,然后按层次输出。

 #include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<sstream>
#include<list>
#include<cmath>
#include<queue>
using namespace std;
struct node{
int index;
node *left,*right;
node()
{
index=;
left=right=NULL;
}
};
int pre[],mid[];
int n2,n;
int judge[];
node* build(node *root)//建树
{
int t=pre[n2++];
int i; for( i=;i<n;i++)
{
if(mid[i]==t)
break;
}
root=new node();
root->index=t;
judge[i]=;
if(i>&&i<n&&judge[i-]==)
root->left=build(root->left);
if(i>=&&i<n-&&judge[i+]==)
root->right=build(root->right);
return root;
} void print(node* root)
{
printf("%d ",root->index); if(root->left)
print(root->left);
if(root->right)
print(root->right);
return ;
}
int cntp=;
void bfs(node* root)//题目要求层次遍历输出
{
queue <node*> q;
q.push(root);
while(!q.empty())
{
node* a=q.front();
q.pop();
if(cntp!=)
printf(" ");
printf("%d",a->index);
cntp++; // system("pause");
if(a->right)
q.push(a->right);
if(a->left)
q.push(a->left); }
return ;
}
int main()
{ while(scanf("%d",&n)==)
{
for(int i=;i<n;i++)
scanf("%d",&mid[i]);
for(int i=;i<n;i++)
scanf("%d",&pre[i]);
memset(judge,,sizeof(judge));
n2=;
cntp=;
node* root=build(root);
//print(root);
bfs(root);
printf("\n");
}
return ;
}

PTA