pat L2-006. 树的遍历(后序+中序->层次)

来源:互联网 发布:php购物车系统设计 编辑:程序博客网 时间:2024/05/16 15:13

L2-006. 树的遍历

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

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

输入格式:

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

输出格式:

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

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

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>#include <vector>#include <map>#include <queue>#include <string>using namespace std;const int N = 10010;vector<int>p[N];int a[N], b[N],  n, tree[100000];void dfs(int rt,int l,int r,int l1,int r1){    if(l>r||l1>r1) return ;    int pos=r1;    if(l==r)    {        tree[rt]=a[pos];        return ;    }    tree[rt]=a[pos];    int i,j=0;    for(i=l; i<=r; i++,j++)    {        if(b[i]==a[pos])        {            dfs(rt*2,l,i-1,l1,l1+j-1);            dfs(rt*2+1,i+1,r,l1+j,r1-1);            break;        }    }    return ;}int main(){    scanf("%d", &n);    for(int i=0; i<=n; i++) p[i].clear();    for(int i=1; i<=n; i++) scanf("%d", &a[i]);    for(int i=1; i<=n; i++) scanf("%d", &b[i]);    memset(tree,-1,sizeof(tree));    dfs(1,1,n,1,n);    int flag=0;    for(int i=1;; i++)    {        if(tree[i]==-1) continue;        if(flag==0) printf("%d",tree[i]),flag=1;        else printf(" %d",tree[i]),flag++;        if(flag==n) break;    }    printf("\n");    return 0;}

0 0
原创粉丝点击