本文共 1699 字,大约阅读时间需要 5 分钟。
#include#include #include using namespace std;int n;const int maxn = 31;struct node { int data; node *l, *r;};vector 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 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;}
转载地址:http://cmvta.baihongyu.com/