PAT--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 <bits/stdc++.h>
#include <cstring>
using namespace std;

int n;
int postOrder[50],inOrder[50];

struct TreeNode{
    int data;
    TreeNode* lchild;
    TreeNode* rchild;
};

int num = 0;
void layerTrave(TreeNode* root){
    queue<TreeNode*> q;
    q.push(root);
    while(!q.empty()){
        TreeNode* tmp;
        tmp = q.front();
        q.pop();
        cout<<tmp->data;
        num++;
        if(num<n) cout<<" ";
        if(tmp->lchild!=NULL)
            q.push(tmp->lchild);
        if(tmp->rchild!=NULL){
            q.push(tmp->rchild);
        }

    }

}

TreeNode* create(int postL,int postR,int intL,int intR){
    if(postL>postR){
        return NULL;
    }
    TreeNode* root = new TreeNode;
    root->data = postOrder[postR];
    int k;
    for(int i=intL;i<=intR;i++){
        if(inOrder[i]==postOrder[postR]){
            k = i;
            break;
        }
    }

    int numLeft = k-intL;
    root->lchild = create(postL,postL+numLeft-1,intL,k-1);
    root->rchild = create(postL+numLeft,postR-1,k+1,intR);
    return root;
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>postOrder[i];
    }
    for(int i=0;i<n;i++){
        cin>>inOrder[i];
    }

    TreeNode* root = create(0,n-1,0,n-1);

    layerTrave(root);

    return 0;
}

注:

队列使用的元素是TreeNode*,而不是TreeNode。这是因为在队列中保存的只是原元素的一个副本,因此如果队列中直接存放TreeNode型,当需要修改队首元素的时候,就会无法对原元素进行修改。

猜你喜欢

转载自blog.csdn.net/jackson_j/article/details/98654680