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; }
相关文章推荐
- 1127. ZigZagging on a Tree (30)
- PAT (Advanced Level) Practise 1127 ZigZagging on a Tree (30)
- PAT 1127. ZigZagging on a Tree (30) 建树+双端队列 随后再看
- 1127. ZigZagging on a Tree (30) PAT 甲级
- 1127.ZigZagging on a Tree (30)
- PAT-1127. ZigZagging on a Tree (30)
- PAT_A 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- PAT甲级 1127. ZigZagging on a Tree (30)
- PAT - 甲级 - 1127. ZigZagging on a Tree (30) ( 树的层次遍历变形 )
- pat 1127. ZigZagging on a Tree (30) 递归建树 + BFS
- 【PAT】【Advanced Level】1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)[二叉树构建-dfs-bfs]
- 1127. ZigZagging on a Tree (30)
- PAT 1127. ZigZagging on a Tree (30)-甲级
- PAT 1127. ZigZagging on a Tree (30) 树的构建+特殊遍历序列
- PAT 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- PAT (Advanced Level)1127. ZigZagging on a Tree (30)