您的位置:首页 > 其它

1020. Tree Traversals (25)

2015-01-04 14:38 190 查看
#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]
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: