构造树的结构,记录每个节点左右的孩子节点数,从而判断其数值的大小位置。
#include <iostream>
#include <algorithm>
#include <queue>
#include <stdio.h>
using namespace std;
struct Info
{
int left;
int leftNodes;
int right;
int rightNodes;
int total;
int value;
};
int n;
int *num;
Info *tree;
void build(int root, int start)
{
if(root == -1)
return;
tree[root].value = num[tree[root].leftNodes + start];
build(tree[root].left, start);
build(tree[root].right, 1+tree[root].leftNodes + start);
}
int calcunums(int root)
{
if(root == -1)
return 0;
if(tree[root].left == -1)
tree[root].leftNodes = 0;
else
tree[root].leftNodes = calcunums(tree[root].left)+1;
if(tree[root].right == -1)
tree[root].rightNodes = 0;
else
tree[root].rightNodes = calcunums(tree[root].right)+1;
tree[root].total = tree[root].leftNodes + tree[root].rightNodes;
return tree[root].total;
}
int main()
{
scanf("%d", &n);
num = new int[n];
tree = new Info[n];
for(int i = 0; i < n; i++)
scanf("%d %d", &(tree[i].left), &(tree[i].right));
for(int i = 0; i < n; i++)
scanf("%d", num+i);
sort(num, num+n);
calcunums(0);
build(0, 0);
bool first = true;
queue<Info> output;
Info info;
output.push(tree[0]);
while(!output.empty())
{
info = output.front();
output.pop();
if(first)
cout << info.value;
else
cout << " " << info.value;
first = false;
if(info.left != -1)
output.push(tree[info.left]);
if(info.right != -1)
output.push(tree[info.right]);
}
return 0;
}