1127. ZigZagging on a Tree (30)

很简单的题,先根据中序排序,与后序排序递归建树,然后层次遍历存入到out数组中,用now存储当前遍历的先后次序,用level来存储当前层数,date存储数据。用sort结构体排序,不同层次按从小到到排。相同层次,如果是奇数层,按now大到小排,如果为偶数层,按now的大小到大排。

#include 
#include
#include
#include
#include
#include
#include
using namespace std;

struct tree{
    int data,level;
    tree * left;
    tree *right;
};
struct node{
    int data;
    int now;
    int level;
    friend bool operator < (node a1,node a2)
    {
        if(a1.level!=a2.level)
        return a1.levelelse 
        {
            if(a1.level%2)
            return a1.now>a2.now;
            else
            return a1.nowvector<int>in,post;
vectorout;
tree * build(int le1,int rig1,int le2,int rig2,int level)
{
    if(le1>rig1)
    return NULL;
    int position;
    for(int i=le1;i<=rig1;i++)
    if(in[i]==post[rig2])
    {
        position=i;
        break;
    }
    tree *temp;
    temp=(tree *)malloc(sizeof(tree));
    temp->data=post[rig2];
    temp->level=level;
    temp->left=build(le1,position-1,le2,le2+(position-le1-1),level+1);
    temp->right=build(position+1,rig1,le2+(position-le1),rig2-1,level+1);
    return temp;
}
queueque;
int main()
{
    int N;
    cin>>N;
    for(int i=1;i<=N;i++)
    {
        int temp;
        scanf("%d",&temp);
        in.push_back(temp);
    }
    for(int i=1;i<=N;i++)
    {
        int temp;
        scanf("%d",&temp);
        post.push_back(temp);
    }
    tree * root;
    root=build(0,N-1,0,N-1,1);
    que.push(root);
    int now=1;
    while(!que.empty())
    {
        tree * temp;
        temp=que.front();
        que.pop();
        node n;
        n.data=temp->data;
        n.now=now++;
        n.level=temp->level;
        out.push_back(n);
        if(temp->left!=NULL)
        que.push(temp->left);
        if(temp->right!=NULL)
        que.push(temp->right);
    }
    sort(out.begin(),out.end());
    for(int i=0;iif(i!=0)cout<<" "<else cout<return 0;
}

你可能感兴趣的:(pat)