1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <iostream> #include <vector> #include <stdio.h> #include <queue>
using namespace std;
struct TreeNode { TreeNode* left; TreeNode* right; int No; };
bool myfind(vector<int> a, int num){ for (int i : a) { if ( i == num) return true; } return false; }
void build(vector<int> b_ord, vector<int> m_ord, TreeNode* root){ int size = b_ord.size(); root->No = b_ord[size-1]; if (size == 1) { root->left = nullptr; root->right = nullptr; return; } TreeNode* l = new TreeNode(); TreeNode* r = new TreeNode(); vector<int> l_mid; vector<int> r_mid; vector<int> l_behind; vector<int> r_behind; bool f = false; for (int i = 0; i < size; i++) { if (b_ord[size-1] == m_ord[i]) f = true; else { if (!f) l_mid.push_back(m_ord[i]); else r_mid.push_back(m_ord[i]); } } for (int i = 0; i < size; i++) { if (myfind(l_mid, b_ord[i])) { l_behind.push_back(b_ord[i]); } if (myfind(r_mid, b_ord[i])) { r_behind.push_back(b_ord[i]); } } if (l_mid.size() > 0) build(l_behind, l_mid, l); else l = nullptr; if (r_mid.size() > 0) build(r_behind, r_mid, r); else r = nullptr; root->left = l; root->right = r; return; }
void visit(TreeNode* root, int n){ queue<TreeNode*> q; q.push(root); int cnt = 0; while (!q.empty()) { TreeNode* p = q.front(); q.pop(); if (cnt != n-1) cout << p->No << ' '; else cout << p->No; cnt++; if (p->left) q.push(p->left); if (p->right) q.push(p->right); } }
int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int n; cin >> n;
vector<int> behind_ord(n, 0); vector<int> mid_ord(n, 0); for (int i = 0; i < n; i++) { cin >> behind_ord[i]; } for (int i = 0; i < n; i++) { cin >> mid_ord[i]; }
TreeNode* root = new TreeNode(); build(behind_ord, mid_ord, root);
visit(root, n); return 0; }
|