码迷,mamicode.com
首页 > 其他好文 > 详细

L2-006 树的遍历

时间:2019-03-22 20:18:15      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:pac   empty   queue   class   pop   mes   namespace   ace   nbsp   

#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] << " \n"[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);
}

 

L2-006 树的遍历

标签:pac   empty   queue   class   pop   mes   namespace   ace   nbsp   

原文地址:https://www.cnblogs.com/ALINGMAOMAO/p/10580697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!