1127. ZigZagging on a Tree (30) (中序,后序,求层序)

来源:互联网 发布:windows xp vol key 编辑:程序博客网 时间:2024/06/08 15:07

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in “zigzagging order” – that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

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 inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the zigzagging sequence of the tree in a line. 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:
812 11 20 17 1 15 8 512 20 17 11 15 8 5 1
Sample Output:
1 11 5 8 17 12 20 15

此题类似于pat甲级1020

只需要重载运算符,并且在结构体中加入层数属性

#include<iostream>#include<queue>using namespace std;struct tree{int num;long weight;int leval;};bool operator <(const struct tree x,const struct tree y){    if (x.leval==y.leval)    {        if (x.leval&1==1)             return x.weight<y.weight;//如果是奇数层,那么右边的优先级大于左边优先级        else             return x.weight>y.weight;//反之亦然    }    else//如果不在同一层,那么上面的优先级大于下面的优先级         return x.weight>y.weight;}priority_queue <struct tree> q;void fun(int x[],int y[],int len,long weight, int leval ){    if (len<=0) return ;    struct tree temp={x[len-1],weight,leval};    q.push(temp);    int index=0;    while(y[index]!=x[len-1]) index++;    fun(x,y,index,weight*2,leval+1);    fun(x+index,y+index+1,len-index-1,weight*2+1,leval+1);}int main(){    int n;    int post[50],in[50];    cin>>n;    for (int i=0;i<n;i++)        cin>>in[i];    for (int i=0;i<n;i++)        cin>>post[i];    fun(post,in,n,1,1);    while(!q.empty())    {        cout<<q.top().num;        q.pop();        if (!q.empty())            cout<<" ";    }    return 0;}