• 1020 Tree Traversals (25分)


    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 (≤), 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<algorithm>
    #include<cstdio>
    #include<cstdlib>
    #include<vector>
    #include<cmath>
    #include<cstring>
    #include<queue>
    #include<string.h>
    using namespace std;
    typedef long long ll;
    const int maxn=10010;
    int post[maxn];
    int in[maxn];
    int level[maxn];
    
    void f(int root,int start,int end,int index) {//通过后序遍历根节点,确定中序遍历根节点下标,存入层序遍历数组中,再递归中序的左和右子树
    //root 后序遍历根节点位置 //start 中序遍历序列首地址,end: 中序遍历序列尾地址   index :满二叉树中层次结点的下标(根节点在层次序列中的位置)
        if(start>end)//中序序列长度为0,该子树遍历结束
        {
            return ;
        }
        int i=start;//i为中序遍历中根节点的下标
        while(i<end&&in[i]!=post[root]){//通过后序根节点,确定中序根节点下标
            i++;
        }
        level[index]=post[root];//根节点位置存入层序遍历数组
        f(root-(end-i+1),start,i-1,2*index+1);//递归遍历左子树
        f(root-1,i+1,end,2*index+2);//递归遍历右子树
    }
    
    int main() {
        int N;
        memset(level,-1,sizeof(level));
        scanf("%d",&N);
        for(int i=0; i<N; i++) {
            scanf("%d",&post[i]);
        }
        for(int i=0; i<N; i++) {
            scanf("%d",&in[i]);
        }
        f(N-1,0,N-1,0);
        //如果不是满二叉树,index的值非连续,所以数组的下标非连续
        int cnt=0;
        for(int i=0;i<maxn; i++) {
            if(level[i]!=-1){
                if(cnt<N-1){
                    printf("%d ",level[i]);
                }
                else{
                    printf("%d
    ",level[i]);
                }
                if(cnt>N){
                    break;
                }
                cnt++;
            }
        }
        return 0;
    }
  • 相关阅读:
    C#使用Task创建任务
    Java编程思想学习(二)一切都是对象
    Java编程思想学习(一)对象导论中多态的理解
    【源码】sql__备份数据库1__bak数据库__存储过程
    【源码】自己写的Msg
    【情感】女人永远是期望男人主动的
    sql函数 手机品牌
    【源码】继承pagebase 权限判断
    【源码】Sql Server 2005 如何自动备份数据库
    sql 将smslog拆分3天3月内,3月外表
  • 原文地址:https://www.cnblogs.com/dreamzj/p/14323018.html
Copyright © 2020-2023  润新知