L2-006 树的遍历

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 100;
int af[maxn], in[maxn], n;
struct node{
    int l, r;
}tree[maxn];

int biuld(int al, int ar, int bl, int br){
    if (al > ar)return 0;
    int root, p1, len;
    root = af[br];
    for (p1 = al; p1 <= ar; ++p1)if (in[p1] == root)break;
    len = p1 - al;
    tree[root].l = biuld(al, p1 - 1, bl, bl + len-1);
    tree[root].r = biuld(p1 + 1, ar, bl + len, br - 1);
    return root;
}

void BFS(int x){
    queue<int>q;
    vector<int>v;
    q.push(x);
    while (!q.empty()){
        int root = q.front();    q.pop();
        if (root == 0)break;
        v.push_back(root);
        if (tree[root].l)q.push(tree[root].l);
        if (tree[root].r)q.push(tree[root].r);
    }
    int len = v.size();
    for (int i = 0; i < len; ++i)
        cout << v[i] << " 
"[i == len - 1];
}

int main(){
    cin >> n;
    for (int i = 0; i < n; ++i)cin >> af[i];
    for (int i = 0; i < n; ++i)cin >> in[i];
    int root = biuld(0, n - 1, 0, n - 1);
    BFS(root);
}
原文地址:https://www.cnblogs.com/ALINGMAOMAO/p/10580697.html