#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
#define N 30
struct TreeNode {
int key;
TreeNode * left;
TreeNode * right;
};
TreeNode * create(int in[], int post[], int ia, int ib, int pa, int pb) {
TreeNode * t = NULL;
if(ia <= ib) {
t = new TreeNode;
t->key = post[pb];
int index = 0;
while(in[index] != post[pb]) index ++;
t->left = create(in, post, ia, index-1, pa, pa+(index-ia)-1);
t->right = create(in, post, index+1, ib, pa+(index-ia), pb-1);
}
return t;
}
int main(int argc, char **argv) {
int n;
int keys[2][N];
cin >> n;
for(int i = 0; i < 2; i ++) {
for(int j = 0; j < n; j++) {
cin >> keys[i][j];
}
}
TreeNode * root = create(keys[1], keys[0], 0, n-1, 0, n-1);
vector<int> lo;
queue<TreeNode *> lq;
lq.push(root);
while(lq.size()) {
TreeNode * t = lq.front();
lq.pop();
lo.push_back(t->key);
if(t->left)
lq.push(t->left);
if(t->right)
lq.push(t->right);
delete t;
}
cout << lo[0];
for(int i = 1; i < lo.size(); i ++) {
cout << ' ' << lo[i];
}
cout << endl;
return 0;
}
1020. Tree Traversals (25)
最新推荐文章于 2019-12-30 20:23:19 发布