2020-11-08补题报告
玩转二叉树
下附代码:
#include <bits/stdc++.h> using namespace std; struct node{ int data; node *left_child, *right_child; }; int a[110], b[110], k = 1; bool vis[110]; vector<node*> ans; node* build_tree(int l, int r){ if(l > r) return NULL; node* root; root = NULL; for(int i = l;i <= r; ++ i){ if(a[i] == b[k]){ root = new node; root->data = b[k++]; root->right_child = build_tree(l, i - 1); root->left_child = build_tree(i + 1, r); break; } } return root; } void build(node* root){ queue<node*> q; q.push(root); while(q.size()){ node* tmp = q.front(); q.pop(); ans.push_back(tmp); if(tmp->left_child) q.push(tmp->left_child); if(tmp->right_child) q.push(tmp->right_child); } } int n; int main() { cin >> n; for(int i = 1;i <= n; ++ i) cin >> a[i]; for(int i = 1;i <= n; ++ i) cin >> b[i]; node* root = NULL; root = build_tree(1, n); build(root); // cout << ans.size() << endl; for(int i = 0;i < ans.size();++ i){ if(i == ans.size() - 1) cout << ans[i]->data; else cout << ans[i]->data << " "; } }