PAT (Advanced Level) Practise 1020. Tree Traversals (25)

来源:互联网 发布:2015最新网络神曲 编辑:程序博客网 时间:2024/04/29 19:23

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
72 3 1 5 7 6 41 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

提交代码

#include <iostream>using namespace std;int main(){    int n,i,t,w,flag=1;    int postorder[40];    int inorder[40];    int a[40],b[40],c[40],d[40];    cin>>n;    for(i=1;i<=n;i++)        cin>>postorder[i];    for(i=1;i<=n;i++)        cin>>inorder[i];    t=0;    w=0;    a[t]=1;    b[t]=n;    c[t]=1;    d[t]=n;    while(t<=w)    {        if(flag)        {            cout<<postorder[b[t]];            flag=0;        }        else            cout<<" "<<postorder[b[t]];        for(i=c[t];i<=d[t];i++)            if(postorder[b[t]]==inorder[i])            {                if(i-1>=c[t])                {                    w++;                    a[w]=a[t];                    b[w]=a[t]+i-c[t]-1;                    c[w]=c[t];                    d[w]=i-1;                }                if(i+1<=d[t])                {                    w++;                    a[w]=a[t]+i-c[t];                    b[w]=b[t]-1;                    c[w]=i+1;                    d[w]=d[t];                }                break;            }        t++;    }    system("pause");    return 0;}

0 0
原创粉丝点击