1155 Heap Paths (30分) PAT

  1. 用数组记录二叉树
  2. 用一个深度优先遍历输出
  3. 用两个迭代分别检查是否为最大堆或最小堆
#include <iostream>
#include<cstdio>
#include<vector>

using namespace std;

vector<int> outputdata;

void output() {
    int i;
    for (i = 0; i < outputdata.size() - 1; i++) {
        printf("%d ", outputdata[i]);
    }
    printf("%d\n", outputdata[i]);
}

void DFS(int num[], int N, int now) {
    outputdata.push_back(num[now]);
    if (now * 2 + 1 >= N) {
        output();
    }
    else {
        if (now * 2 + 2 < N) {
            DFS(num, N, now * 2 + 2);
        }
        if (now * 2 + 1 < N) {
            DFS(num, N, now * 2 + 1);
        }
    }
    outputdata.pop_back();
}

bool maxheap(int num[], int N, int now) {
    int left = now * 2 + 1;
    int right = now * 2 + 2;
    if (right < N) {
        return maxheap(num, N, right) && maxheap(num, N, left) && (num[now] >= num[right]) && (num[now] >= num[left]);
    }
    else if (left < N) {
        return maxheap(num, N, left) && (num[now] >= num[left]);
    }
    return true;
}

bool minheap(int num[], int N, int now) {
    int left = now * 2 + 1;
    int right = now * 2 + 2;
    if (right < N) {
        return minheap(num, N, right) && minheap(num, N, left) && (num[now] <= num[right]) && (num[now] <= num[left]);
    }
    else if (left < N) {
        return minheap(num, N, left) && (num[now] <= num[left]);
    }
    return true;
}

int main()
{
    int N;
    scanf("%d", &N);
    int num[1010];
    for (int i = 0; i < N; i++) {
        scanf("%d", &num[i]);
    }

    DFS(num, N, 0);
    bool maxh = maxheap(num, N, 0);
    bool minh = minheap(num, N, 0);
    if (maxh) {
        printf("Max Heap\n");
    }
    else if (minh) {
        printf("Min Heap\n");
    }
    else printf("Not Heap\n");


    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值