PAT 1020 Tree Traversals(根据二叉树中序后序遍历求层次遍历)

PAT1020

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
#include
#include
#include
using namespace std;
typedef struct Bitree {
    int data;
    struct Bitree *left;
    struct Bitree *right;
} tree,*Tree;
tree *Resume( int in[],int post[], int len) {
    if(len<=0)
        return NULL;
    tree* temp=new tree;
    temp->data=*post;
    int i=0;
    while(idata)
            break;
        i++;
    }
    temp->left=Resume(in,post-len+i,i);
    temp->right=Resume(in+i+1,post-1,len-i-1);
    return temp;
}
queueq;
int res[100000+50];
int len=0;
void dfs(Tree t) {
    q.push(t);
    while(!q.empty()) {
        t=q.front();
        q.pop();
        res[len++]=t->data;
        if(t->left!=NULL)
            q.push(t->left);
        if(t->right!=NULL)
            q.push(t->right);
    }
}
int in[100],post[100];
int main() {
    int n;
    cin>>n;
    for(int i=0;i

 

 

 

你可能感兴趣的:(数据结构,PAT)