Sample Input:
9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
Sample Output:
58 25 82 11 38 67 45 73 42
题解:
在二叉搜索树中,对其进行中序遍历的结果是给出的数值序列从小到大的排列顺序,利用该该特性,以中序遍历方式构建二叉树的同时为节点赋值,最后再进行一次层次遍历即可
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct node{
int v;
node* left;
node* right;
};
int b[110][2];
int arr[110];
int n;
int index = 0;
bool cmp(int a,int b){
return a < b;
}
void create(node* &root,int ind){
root = new node();
if(b[ind][0] != -1){
create(root->left,b[ind][0]);
}
root->v = arr[index++];
if(b[ind][1] != -1){
create(root->right,b[ind][1]);
}
}
void bfs(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* temp = q.front();
q.pop();
if(temp->left != NULL){
q.push(temp->left);
}
if(temp->right != NULL){
q.push(temp->right);
}
cout << temp->v;
if(!q.empty()){
cout << " ";
}
}
}
int main(){
cin >> n;
for(int i=0;i<n;i++){
scanf_s("%d %d",&b[i][0],&b[i][1]);
}
for(int i=0;i<n;i++){
scanf_s("%d",&arr[i]);
}
sort(arr,arr+n,cmp);
node* root = new node();
create(root,0);
bfs(root);
system("pause");
return 0;
}