您的位置:首页 > 其它

1127. ZigZagging on a Tree (30)

2018-03-04 13:09 531 查看
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int n;
const int maxn = 31;
struct node { int data; node *l, *r;};
vector<int> post(maxn), in(maxn), ans, lnum(maxn);

node* build(int postL, int postR, int inL, int inR){//根据后序和中序建树
if(postL > postR) return NULL;
node *root = new node;
root->data = post[postR];
int k;
for (k = inL; k <= inR; k++)
if(in[k] == post[postR]) break;
int numLeft = k - inL;
root->l = build(postL, postL + numLeft - 1, inL, k - 1);
root->r = build(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
void dfs(node *root, int depth){//求每一层的个数
if (root == NULL) return;
lnum[depth]++;
if(root->l != NULL) dfs(root->l, depth + 1);
if(root->r != NULL) dfs(root->r, depth + 1);
}
void bfs(node *root){//层序遍历的结果存在ans中
queue<node*> q;
q.push(root);
while (!q.empty()) {
node *now = q.front();
q.pop();
ans.push_back(now->data);
if(now->l) q.push(now->l);
if(now->r) q.push(now->r);
}
}

int main(){
cin >> n;
for(int i = 0; i < n; i++) cin >> in[i];
for(int i = 0; i < n; i++) cin >> post[i];
node *root = build(0, n - 1, 0, n - 1);
dfs(root, 0);
bfs(root);
//z输出
int cnt = 0;
printf("%d", ans[cnt++]);
for (int i = 1; i < maxn;) {
if (i % 2) {
for (int j = 0; j < lnum[i]; j++)
printf(" %d", ans[cnt+j]);
cnt = cnt + lnum[i];
i++;
}else{
for (int j = lnum[i] - 1; j >= 0; j--)
printf(" %d", ans[cnt+j]);
cnt = cnt + lnum[i];
i++;
}
}
cout << endl;

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