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

1020. Tree Traversals (25)

时间:2015-03-13 14:30:25      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:


1020. Tree Traversals (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

提交代码



#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=99999;

#define lson (root<<1)
#define rson (root<<1)+1
#define bug printf("---\n");
int n;
int T[maxn];
int post[maxn];
int in[maxn];
int vis[maxn];
int first=1;
void bfs(int root)//本题  也可以不用这个输出,见下面的注释
{
    queue<int> q;
    memset(vis,false,sizeof(vis));
    vis[root]=true;
    q.push(root);
    while(!q.empty())
    {
        int root=q.front();
        q.pop();
        if(first)printf("%d",T[root]),first=0;
        else printf(" %d",T[root]);
        if(!vis[lson]&&T[lson]!=-1)
        {
            vis[lson]=true;
            q.push(lson);
        }
        if(!vis[rson]&&T[rson]!=-1)
        {
            vis[rson]=true;
            q.push(rson);
        }
    }
}



//中序+后序=建树
//pl为post左边端点,pr为post右端点 il,lr为中序的左右端点
///pr-ir+p-1==pr-(ir-p)-1
void build(int root,int pl,int pr,int il,int ir)
{
    if(pl>pr)return;
    int p=il;
    while(in[p]!=post[pr])p++;//后序判断的根结点,在中序里找出来
    T[root]=post[pr];//当前根结点赋值
    build(lson,pl,pr-ir+p-1,il,p-1);//建立左子树
    build(rson,pr-ir+p,pr-1,p+1,ir);//建立右子树
}

int main()
{
    int m,i,j,k,t;
    freopen("in.txt","r",stdin);
    memset(T,-1,sizeof(T));
    cin>>n;
    for(i=0; i<n; i++)
        cin>>post[i];
    for(i=0; i<n; i++)
        cin>>in[i];
    build(1,0,n-1,0,n-1);

   //第一种的直接输出,因为T数组的存储就是层次的
    vector<int>v;
    for(i=1;i<maxn;i++)if(T[i]!=-1)
        v.push_back(T[i]);
    m=v.size();
    for(i=0;i<=m-2;i++)
        printf("%d ",v[i]);
    printf("%d\n",v[m-1]);

  //第二种的按层次遍历后再输出
    //bfs(1);
    //cout<<endl;
    return 0;
}






1020. Tree Traversals (25)

标签:

原文地址:http://blog.csdn.net/u013167299/article/details/44239941

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