【PAT】【Advanced Level】1020. Tree Traversals (25)

来源:互联网 发布:傲剑降龙数据 编辑:程序博客网 时间:2024/05/16 05:22

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
65536 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


原题链接:

https://www.patest.cn/contests/pat-a-practise/1020

https://www.nowcoder.com/questionTerminal/b1dd2f978d9f49cdb936a5061e590837

思路:

DFS判断

对于一个子树

根节点肯定在 后序序列中 代表这个子树的区间 的末尾

根据根节点在中序序列中寻找,分开左右子树,统计个数并回到后序序列找到子树的根节点

以此类推

最后按层序输出

坑点:

最后的统计或者不用排序,或者一定要用稳定的排序方式(冒泡等),快速排序不稳定

CODE:

#include<iostream>#include<vector>#include<algorithm>using namespace std;int n;int po[31];int io[31];typedef struct S{    int nu;    int flo;};int flor=0;S re[31];int num=0;int mm=0;void fi(int ro,int l,int r,int l1,int r1){    mm=max(mm,flor);    //cout<<ro<<" "<<l<<" "<<r<<" "<<l1<<" "<<r1<<endl;    //cout<<po[ro]<<endl;    S t;    t.nu=po[ro];    t.flo=flor;    re[num]=t;    num++;    if (l==r) return ;    int pos=0;    for (int i=l;i<=r;i++)        if(io[i]==po[ro])    {        pos=i;        break;    }    //cout<<pos<<endl;    int nr=l1+pos-l-1;    if(pos!=l)    {        //cout<<nr<<" "<<l<<" "<<pos-1<<" "<<l1<<" "<<nr-1<<endl;        flor++;        fi(nr,l,pos-1,l1,nr-1);        flor--;    }    if (pos!=r)    {        //cout<<r1<<" "<<pos+1<<" "<<r<<" "<<nr+1<<" "<<r1-1<<endl;        flor++;        fi(r1,pos+1,r,nr+1,r1-1);        flor--;    }    return ;}int main(){    cin>>n;    for (int i=1;i<=n;i++)   cin>>po[i];    for (int i=1;i<=n;i++)   cin>>io[i];    fi(n,1,n,1,n-1);    for (int i=num-1;i>0;i--)        for (int j=0;j<i;j++)    {        if (re[j].flo>re[j+1].flo)        {            S t=re[j];            re[j]=re[j+1];            re[j+1]=t;        }    }    for (int i=0;i<num-1;i++) cout<<re[i].nu<<" ";    cout<<re[num-1].nu;    /*    int re1[31];    int nn=0;    for (int i=0;i<=mm;i++)    for (int j=0;j<num;j++)    {        if (re[j].flo==i)        {            re1[nn]=re[j].nu;            nn++;        }    }    for (int i=0;i<nn-1;i++) cout<<re1[i]<<" ";    cout<<re1[nn-1];    */    return 0;}






阅读全文
0 0
原创粉丝点击