pat 1020

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<cstdio>
#include<iostream>
#include<queue>
using namespace std;
typedef struct node{
    int data;
    node* left;
    node* right;
}node;
int n;
int post[35],in[35];
node* create(int postL,int postR,int inL,int inR){
    if(inL>inR)
        return NULL;
    node* root=new node;
    root->data=post[postR];
    int k;
    for(int i=inL;i<=inR;i++){
        if(in[i]==post[postR]){
            k=i;
            break;
        }    
    }
    k=k-inL;
    root->left=create(postL,postL+k-1,inL,inL+k-1);
    root->right=create(postL+k,postR-1,inL+k+1,inR);
    return root;
}
void BFS(node* root){
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node* temp=q.front();
        if(temp->left!=NULL)
            q.push(temp->left);
        if(temp->right!=NULL)
            q.push(temp->right);
        if(temp!=root)
            printf(" %d",temp->data);
        else
            printf("%d",temp->data);
        q.pop();
    } 
}
int main(){
    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]);
    }
    node* root=create(0,n-1,0,n-1);
    BFS(root);
    return 0;
} 
原文地址:https://www.cnblogs.com/foodie-nils/p/13288895.html