1. 程式人生 > 實用技巧 >2020-11-08補題報告

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 << " "; } }