1127. ZigZagging on a Tree (30)

34 篇文章 0 订阅

思路:

递归建树,层序存储,输出


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <map>
#include <queue>
#include <vector>
using namespace std;
typedef struct tree* treebin;
struct tree
{
    treebin left,right;
    int num,lv;
};
vector<int >a[35];
int In[35];

int Post[35];
treebin root = new tree ;
treebin Build(int Inst[],int  Pst[],int len )
{
    treebin p=new tree;
    if(!len)
        return NULL;
    int pos=0;
    for(int i=0;i<len;i++)
    {
        if(Pst[len-1]==Inst[i])
        {
            pos=i;
            break;
        }
    }
    p->num=Inst[pos];
    p->right=Build(Inst+pos+1,Pst+pos,len-pos-1);
    p->left=Build(Inst,Pst,pos);
    return p;

}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>In[i];
    }
    for(int i=0;i<n;i++)
    {
        cin>>Post[i];
    }
    root=Build(In,Post,n );
    root->lv=1;
    queue<treebin>q;
    q.push(root);
    int cnt=1,maxx=0;

    while(!q.empty() )
    {
        treebin ft=q.front();
        q.pop();
        if(ft->left)
        {
        ft->left->lv=ft->lv+1;
        maxx=max(maxx,ft->lv+1);
        q.push(ft->left);
        }
        if(ft->right)
        {
        ft->right->lv=ft->lv+1;
        maxx=max(maxx,ft->lv+1);
        q.push(ft->right);
        }
        a[ft->lv].push_back(ft->num);
    }
    cout<<root->num;
    for(int i=2;i<=maxx;i++)
    {
        if(i&1)
        {
            for(int j=a[i].size()-1;j>=0;j--)
            {
                cout<<" "<<a[i][j];
            }
        }
        else
        {
            for(int j=0;j<a[i].size();j++)
            {
                cout<<" "<<a[i][j];
            }
        }
    }
    cout<<endl;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值