2020-03-15

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 (≤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<cstring>
using namespace std;
//本题就是用后序遍历和中序遍历唯一确定二叉树,输出二叉树的层次遍历。 
int post[50];
int inor[50];
int level[10000];
int main(){
    void pre(int root,int start,int end,int index);
    for(int i=0;i<10000;++i){
        level[i] = -1;
    }
    int nodes;
    cin>>nodes;
    for(int i=0;i<nodes;++i){
        cin>>post[i];
    }
    for(int i=0;i<nodes;++i){
        cin>>inor[i];
    }
    pre(nodes-1,0,nodes-1,0);
    int count = 0;
    for(int i=0;i<10000&&count<nodes;++i){
        if(level[i]!=-1&&count<nodes-1){
            printf("%d ",level[i]);
            count++;
        }else if(level[i]!=-1&&count==nodes-1){
            printf("%d",level[i]);
            break;
        }
    }
}
//先用后续遍历确定根节点,然后用根节点在中序遍历中进行划分。中序遍历不仅划分了左右子树,还划分了左右子树节点的个数。 
//post后序遍历,inor中序遍历,start开始的数组下标,end结束的数组下标,index用于记录层次遍历。
//调用时index为0表示根节点,递归时index为2*index+1左子树,2*index+2右子树。 
void pre(int root,int start,int end,int index){
    //划分完毕时,start大于end,跳出 
    if(start>end)
        return;
    //下面语句进行划分,通过后续遍历确定的根节点,中序遍历将剩下的节点划分为左子树上的和右子树。
    int i = start;
    while(i<end&&inor[i]!=post[root]){
        i++;
    }
    //此次划分的根节点保存下来。 
    level[index] = post[root]; 
    //递归左子树,右子树。 
    //root-(end-i+1)为左子树的节点数,也是根节点。
    //如果使用i-1作为root传入时,哪会跳出这段长度。 
    pre(root-(end-i+1),start,i-1,2*index+1);
    pre(root-1,i+1,end,2*index+2);
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。