structnode { int val; int left, right, parent; } N[100];
intmain() { #ifdef _DEBUG freopen(__FILE__ ".txt", "r", stdin); // freopen(__FILE__ ".out", "w", stdout); #endif int first = 1;
int n; cin >> n; N[0].parent = -1; for (int i = 0; i < n; i++) { int l, r; cin >> l >> r; N[i].left = l; N[l].parent = i; N[i].right = r; N[r].parent = i; }
vector<int> vals; for (int i = 0; i < n; i++) { int val; cin >> val; vals.push_back(val); } sort(vals.begin(), vals.end());
int p = 0; while (N[p].left != -1) { if (N[p].left != -1) p = N[p].left; }
while (p != -1) { debug(p); N[p].val = vals.front(); vals.erase(vals.begin());
if (N[p].right != -1) { // right down p = N[p].right; while (N[p].left != -1) { p = N[p].left; } } elseif (N[p].parent != -1 && N[N[p].parent].left == p) { // right up p = N[p].parent; } else { while (N[p].parent != -1 && N[N[p].parent].right == p) { p = N[p].parent; } p = N[p].parent; } }
queue<int> Q; Q.push(0); while (Q.size()) { int top = Q.front(); Q.pop(); if (!first) cout << " "; else first = 0; cout << N[top].val; if (N[top].left != -1) Q.push(N[top].left); if (N[top].right != -1) Q.push(N[top].right); }