题目很简单,主要是建树要思考下.
我用的是队列,按层次来建的.
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <memory.h>
#include <queue>
using namespace std;
const int maxn = 130;
int treVal[maxn], tree[maxn];
int n, L;
struct node{
int idx, cnt, l, r; //结点索引值, 结点的子节点数量, 排序后的数组的两个范围.
node(int ii = 0, int cc = 0, int ll = 0,int rr = 0):idx(ii), cnt(cc), l(ll), r(rr){}
};
void buildTree(){
queue<node> q;
q.push(node(1, n - 1, 1, n));
while (q.size()){//广度优先建树
node t = q.front(); q.pop();
int idx = t.idx, cnt = t.cnt, l = t.l, r = t.r;
if(cnt > 0){
int lcnt = 0, rcnt = 0;
scanf("%d", &lcnt), scanf("%d", &rcnt);
if(lcnt > 0){
q.push(node(idx << 1, lcnt - 1, l, l + lcnt - 1));
}
if(rcnt > 0){
q.push(node(idx << 1 | 1, rcnt - 1, l + lcnt + 1, r));
}
tree[idx] = treVal[l + lcnt];
}else{
tree[idx] = treVal[l];
}
}
}
void postOrder(int idx,int & c){
if(tree[idx] >= 0){
postOrder(idx << 1, c);
postOrder(idx << 1 | 1, c);
if(c++ > 0 )printf(" ");
printf("%d",tree[idx]);
}
}
int main(){
while (~scanf("%d", &n)){
memset(tree, -1, sizeof(tree));
for (int i = 1; i <= n; ++i){
scanf("%d", &treVal[i]);
}
sort(treVal + 1, treVal + n + 1);
scanf("%d", &L);
buildTree();
int c = 0;
postOrder(1, c);
printf("\n");
}
return 0;
}