利用中序遍历法构造二叉搜索树,再用bfs的思想 对构造的树进行层序遍历
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct node{
int key;
int right,left;
};
node num[100];
int keys[100];
int now=0;
vector <int> ans;
queue<int>q;
int j=0;
void travel(int i){
if(num[i].left!=-1) travel(num[i].left);
num[i].key=keys[j++];
if(num[i].right!=-1) travel(num[i].right);
return;
}
void bfs(int cur){
ans.push_back(num[cur].key);
if(num[cur].left!=-1) q.push(num[cur].left);
if(num[cur].right!=-1) q.push(num[cur].right);
if(q.size()>0){
int temp;
temp=q.front();
q.pop();
bfs(temp);
}
return;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int num1,num2;
cin>>num1>>num2;
num[i].left=num1;
num[i].right=num2;
}
for(int i=0;i<n;i++){
cin>>keys[i];
}
sort(keys,keys+n);//将数字递增排序,中序遍历的访问顺序和数字的位次一样
travel(0);//中序遍历,构造二叉搜索树
bfs(0);//左子树优先的广度优先遍历
for(int i=0;i<n;i++) {
cout<<ans[i];
if(i!=n-1) cout<<" ";
}
}