#include<bits/stdc++.h>
using namespace std;
typedef struct Tree* tree;
struct Tree{
int id=-1;
int num;
tree left=NULL;
tree right=NULL;
};
tree nodeptr[110]={0};
int key[110];
int nodesize[110]={0}; //nodesize[i]记录id等于i的结点为根的子树的大小
//返回子树node结点的个数
int findsize(tree node){
if(node==NULL)
return 0;
else if(nodesize[node->id]!=0){
return nodesize[node->id];
}else{
nodesize[node->id]=findsize(node->left)+findsize(node->right)+1;
return nodesize[node->id];
}
}
bool cmp(const int &a,const int &b){
return a<b;
}
//将数组从key[h]~key[r]的数填入子树node之中
void fillnum(tree node,int h,int r){
if(h>r) return;
int leftsize=findsize(node->left);
int rightsize=r-h-leftsize;
node->num=key[h+leftsize];
fillnum(node->left,h,h+leftsize-1);
fillnum(node->right,r-rightsize+1,r);
}
int main(){
int n;
cin>>n;
tree root=new Tree;
nodeptr[0]=root;
root->id=0;
int l,r;
for(int i=0;i<n;i++){
cin>>l>>r;
if(l!=-1){
tree leftsub=new Tree;
leftsub->id=l;
nodeptr[i]->left=leftsub;
nodeptr[l]=leftsub;
}
if(r!=-1){
tree rightsub=new Tree;
rightsub->id=r;
nodeptr[i]->right=rightsub;
nodeptr[r]=rightsub;
}
}
for(int i=0;i<n;i++)
cin>>key[i];
sort(key,key+n,cmp);
fillnum(nodeptr[0],0,n-1);//把数填入到树中
queue<tree> que;
que.push(nodeptr[0]);
while(!que.empty()){
tree thenode=que.front();
cout<<thenode->num;
if(thenode->left!=NULL)
que.push(thenode->left);
if(thenode->right!=NULL)
que.push(thenode->right);
que.pop();
if(!que.empty())
cout<<" ";
}
return 0;
}
pat1099
猜你喜欢
转载自www.cnblogs.com/moderateisbest/p/10416165.html
今日推荐
周排行