L2-006. 树的遍历

2016年团体程序设计天梯赛-模拟赛

给定中序遍历和后序遍历求前序遍历。给前序遍历和中序遍历求后序遍历这样类型的题目,可以先构造成一颗二叉树,然后。。。就好办了
 
 

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

后序遍历的最后一个节点是树根。然后从根节点递归左子树,右子树。构造二叉树。然后bfs一遍,求层次序列。

/* ***********************************************
Author        :guanjun
Created Time  :2016/5/15 19:30:57
File Name     :1.cpp
************************************************ */
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <deque>
#include <stack>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 10010
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
struct node{
    int l,r;
}nod[maxn];
int in[maxn];
int po[maxn];
int build(int l1,int r1,int l2,int r2){
    if(l1>r1)return 0;
    int root=po[r2];
    int p=l1;
    while(in[p]!=root)p++;
    int cnt=p-l1;
    nod[root].l=build(l1,p-1,l2,l2+cnt-1);
    nod[root].r=build(p+1,r1,l2+cnt,r2-1);
    return root;
}

void bfs(int x){
    queue<int>q;
    q.push(x);
    vector<int>v;
    while(!q.empty()){
        int w=q.front();q.pop();
        if(w==0)break;
        v.push_back(w);
        if(nod[w].l!=0)q.push(nod[w].l);
        if(nod[w].r!=0)q.push(nod[w].r);
    }
    int m=v.size();
    for(int i=0;i<m;i++){
        printf("%d%c",v[i],i==m-1?10:' ');
    }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
    //freopen("out.txt","w",stdout);
    int n;
    while(cin>>n){
        for(int i=1;i<=n;i++)cin>>po[i];
        for(int i=1;i<=n;i++)cin>>in[i];
        build(1,n,1,n);
        int root=po[n];
        bfs(root);
    }
    return 0;
}

紫书上例题..

posted on 2016-05-15 20:30  Beserious  阅读(1403)  评论(0编辑  收藏  举报