PAT (Advanced Level) Practice A1155 Heap Paths (30 分) (C++)(甲级)(堆、最小二叉树)

原题链接

#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 1010;
int N, tag = 0;
int T[MAX];

vector<int> path;//用path存储每条路径
void preOrder(int root)
{
    int lChild = root*2;
    int rChild = lChild + 1;
    path.push_back(T[root]);
    if(rChild <= N)
    {
        preOrder(rChild);
        if(tag == 1 && T[root] < T[rChild]//刚开始判断为大/小根堆,但这里出现了异常
           || tag == 2 && T[root] > T[rChild]) tag = 3;
    }
    if(lChild <= N)
    {
        preOrder(lChild);
        if(tag == 1 && T[root] < T[lChild]
           || tag == 2 && T[root] > T[lChild]) tag = 3;
    }
    if(lChild > N && rChild > N)//到了叶节点,打印路径
    {
        printf("%d", path[0]);
        for(int i=1; i<path.size(); i++)
        {
            printf(" %d", path[i]);
        }
        printf("\n");
    }
    path.pop_back();
}

int main()
{
    scanf("%d", &N);
    for(int i=1; i<=N; i++) scanf("%d", &T[i]);
    if(T[1] > T[2]) tag = 1;//大根堆
    else tag = 2;//小根堆
    preOrder(1);
    if(tag == 1) printf("Max Heap\n");
    else if(tag == 2) printf("Min Heap\n");
    else if(tag == 3) printf("Not Heap\n");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值