ZJU 3170 7 Levels of Binary Search Tree

题目链接:

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3170

题意:

给你一个n,里面有n个点,然后再给出一个m,下面有m-1行的数据,每一行的数据个数是不定的,需要自己计算输入。但是大致上是这样给的,每一行都会给出父结点的左子树的结点的总个数,以及右子树结点的个数。这样,会构成一颗二叉搜索树,让你以后序遍历的方式输出这颗树。
题解:
解决好输入的问题( 第一行的输入一定只有两个,第二行开始的输入的个数,可以通过找上一行中2出现的个数*2),然后就是以深搜递归的方式去确定,这里就不详细讲了,直接看代码。
代码:

#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1000+10;
queue<int>q[maxn];
int num[maxn];
int ans[maxn];

void dfs(int left,int right,int cnt,int a,int b,int MM,int MX)
{
    ans[right]=num[MM+a];
    if(a==1)
    {
        ans[left]=num[MM+a-1];
    }
    else if(a>=2)
    {
        int depth=cnt+1;
        int tempa=0,tempb=0;
        tempa=q[depth].front();
        q[depth].pop();
        tempb=q[depth].front();
        q[depth].pop();
        dfs(left,left+a-1,depth,tempa,tempb,MM,MM+a-1);
    }
    if(b==1)
    {
        ans[right-1]=num[MM+a+1];
    }
    else if(b>=2)
    {
        int depth=cnt+1;
        int tempa=0,tempb=0;
        tempa=q[depth].front();
        q[depth].pop();
        tempb=q[depth].front();
        q[depth].pop();
        dfs(left+a,right-1,depth,tempa,tempb,MM+a+1,MX);
    }
}


int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            while(!q[i].empty())
                q[i].pop();
        }
        met(ans,0);
        for(int i=1;i<=n;i++)
            scanf("%d",&num[i]);
        sort(num+1,num+1+n);
        int m;
        scanf("%d",&m);
        if(n==1)
        {
            printf("%d\n",num[1]);
            continue;
        }
        m-=1;
        int cnt=1;
        int next_cnt=0;
        int len=0;
        while(m--)
        {
            cnt*=2;
            next_cnt=0;
            while(cnt--)
            {
                int x=0;
                scanf("%d",&x);
                q[len].push(x);
                if(x>=2)
                    next_cnt++;
            }
            len++;
            cnt=next_cnt;
        }
        int ans1=q[0].front();
        q[0].pop();
        int ans2=q[0].front();
        q[0]. pop();
        dfs(1,n,0,ans1,ans2,1,n);
        for(int i=1;i<=n;i++)
        {
            printf("%d",ans[i]);
            if(i!=n)
                printf(" ");
            else
                printf("\n");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值