本题是由已知二叉树遍历得到中序遍历序列的逆用.
已知二叉树中序遍历序列,将每个结点的权重存入二叉树.
用数组存储,遍历过程与链表一致,由数组下标指向左右孩子代替链表指针指向左右孩子.
同类型题:A1064.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=110;
int t[maxn],idx=0;
struct node{
int data;
int left_index;
int right_index;
}nodes[maxn];
bool cmp(int a,int b){
return a<b;
}
void inorder(int root){ //中序遍历
if(root==-1){
return;
}
inorder(nodes[root].left_index);
nodes[root].data=t[idx++];
inorder(nodes[root].right_index);
}
void levelorder(int root){ //层序遍历
queue<int> q;
q.push(root);
while(!q.empty()){
int now=q.front();
q.pop();
if(nodes[now].left_index!=-1){
q.push(nodes[now].left_index);
}
if(nodes[now].right_index!=-1){
q.push(nodes[now].right_index);
}
printf("%d",nodes[now].data);
if(!q.empty()){
printf(" ");
}
}
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&nodes[i].left_index,&nodes[i].right_index);
}
for(int i=0;i<n;i++){
scanf("%d",&t[i]);
}
sort(t,t+n,cmp);
inorder(0);
levelorder(0);
return 0;
}