PAT 甲级 1099 Build A Binary Search Tree
#include <bits/stdc++.h>
using namespace std;
const int kMAXN=110;
int n,key[kMAXN],lchild[kMAXN],rchild[kMAXN];
int nums[kMAXN],idx=0;
void InOrderBuild(int root)
{
if(root==-1) return;
if(lchild[root]!=-1) InOrderBuild(lchild[root]);
if(root!=-1) key[root]=nums[idx++];
if(rchild[root]!=-1) InOrderBuild(rchild[root]);
}
void LevelOrder()
{
queue<int> q;
q.push(0);
while(!q.empty()){
int now=q.front();q.pop();
if(lchild[now]!=-1) q.push(lchild[now]);
if(rchild[now]!=-1) q.push(rchild[now]);
if(now!=0) cout<<" ";
cout<<key[now];
}
}
int main()
{
int n;cin>>n;
for(int i=0;i<n;++i){
cin>>lchild[i];
cin>>rchild[i];
}
for(int i=0;i<n;++i) cin>>nums[i];
sort(nums,nums+n);
InOrderBuild(0);
LevelOrder();
}