PAT A1155 Heap Paths

解法:一次遍历,到达根结点递归输出结点

#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <math.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#define maxn 1010
using namespace std;

int n;
int levelorder[maxn];
bool f1=true,f2=true; // f1为大根堆,f2为小根堆

void to_print(int root,int h)
{
    if(root!=1)to_print(root/2,h+1);
    printf("%d",levelorder[root]);
    if(h!=0)printf(" ");
    else printf("\n");
}

void Traverse(int root)//顺序为:根右左
{
    if(root<=n)
    {
        if(root!=1)//判断是否符合最大堆或者最小堆!
        {
            if(levelorder[root]>levelorder[root/2])f1=false;
            if(levelorder[root]<levelorder[root/2])f2=false;
        }
        if(root*2>n)to_print(root,0);
        Traverse(root*2+1);
        Traverse(root*2);
    }
}

int main()
{
    //freopen("input.txt","r",stdin);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",levelorder+i);
       // printf("%d ",levelorder[i]);
    }
    Traverse(1);
    if(f1)printf("Max Heap\n");
    else if(f2)printf("Min Heap\n");
    else printf("Not Heap\n");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值