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<queue>
using namespace std;
struct node {
    int date;
    node* lt, * rt;
};
int ps[50], in[50],la[50];
node* create(int postl,int postr,int inl,int inr) {
    if (postr-postl<0) {
        return NULL;
    }
    node* root = new node;
    root->date = ps[postr];
    int k;
    for (k = inl; k <=inr; k++) {
        if (in[k]==ps[postr])
            break;
    }
    int ln = k-inl;//左子树个数
    root->lt = create(postl,postl+ln-1,inl,k-1);//建左子树
    root->rt = create(postl+ln,postr-1,k+1,inr);//建右子树
    return root;
}
int out=0,num;
void layer(node* root) {//广度优先搜索
    queue<node*>q;
    q.push(root); 
    int i=0;
    while (!q.empty()) {
        node* n = q.front();
        q.pop();
        la[i++]=n->date;
        if (n->lt != NULL)q.push(n->lt);
        if (n->rt != NULL)q.push(n->rt);
    }
   
}
int main() {    
    cin >> num;
    
    for (int i = 0; i < num; ++i) {
        cin >> ps[i];
    }
    for (int i = 0; i < num; ++i) {
        cin >> in[i];
    }
    node* root = create(0, num - 1, 0, num - 1);
    layer(root);
    for(int i=0;i<num;i++){
        if(i!=0)cout<<" ";
        cout<<*(la+i);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/kalicener/p/12546072.html