typedefstructLNode { int data; structLNode* lc; structLNode* rc; }LNode, *Tree;
Tree creatTree(int postL, int postR, int inL, int inR){ if (postL > postR || inL > inR) returnNULL; LNode* root = new LNode; root->data = post[postR]; int indexRoot; for (indexRoot = inL; indexRoot <= inR; indexRoot++) { if (in[indexRoot] == post[postR]) break; } int lengthOfLeftTree = indexRoot - inL; root->lc = creatTree(postL, postL + lengthOfLeftTree - 1, inL, indexRoot - 1); root->rc = creatTree(postL + lengthOfLeftTree, postR - 1, indexRoot + 1, inR); return root; }
voidBFS(Tree root){ int num = 0; queue<LNode*> q; q.push(root); while (!q.empty()) { LNode* now = q.front(); q.pop(); printf("%d", now->data); num++; if (num < n) printf(" "); if (now->lc != NULL) q.push(now->lc); if (now->rc != NULL) q.push(now->rc); } }
intmain(){ scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &post[i]); } // 后序 for (int i = 0; i < n; i++) { scanf("%d", &in[i]); } // 中序 Tree root = creatTree(0, n - 1, 0, n - 1); BFS(root);
#include<iostream> #include<algorithm> #include<vector> usingnamespacestd; structnode { int index, value; }; boolcmp(node a, node b){ return a.index < b.index; } vector<int> post, in; vector<node> ans; voidpre(int root, int start, int end, int index){ if (start > end) return; int i = start; while (i < end && in[i] != post[root]) i++; ans.push_back({index, post[root]}); pre(root - 1 - end + i, start, i - 1, 2 * index + 1); pre(root - 1, i + 1, end, 2 * index + 2); } intmain(){ int n; scanf("%d", &n); post.resize(n); in.resize(n); for (int i = 0; i < n; i++) scanf("%d", &post[i]); for (int i = 0; i < n; i++) scanf("%d", &in[i]); pre(n - 1, 0, n - 1, 0); sort(ans.begin(), ans.end(), cmp); for (int i = 0; i < ans.size(); i++) { if (i != 0) cout << " "; cout << ans[i].value; } return0; }