PAT甲级 1155 Heap Paths DFS+树的层次遍历

39 篇文章 0 订阅
22 篇文章 0 订阅

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Solution:

//DFS+树的层次遍历

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

struct tree{
    int key;
    int left;
    int right;
    tree(){
        left=right=0;
    }
};

vector<tree> t;
int n;
bool flag1=true,flag2=true;
vector<int> path;

void judge_max(int root){
    if(t[root].left==0&&t[root].right==0){
        return;
    }
    int key=t[root].key;
    if(t[root].left==0){
        if(t[t[root].right].key>key){
            flag1=false;
            return;
        }
    }else if(t[root].right==0){
        if(t[t[root].left].key>key){
            flag1=false;
            return;
        }
    }else{
        if(t[t[root].left].key>key||t[t[root].right].key>key){
            flag1=false;
            return;
        }
    }
    if(t[root].left!=0){
        judge_max(t[root].left);
    }
    if(t[root].right!=0){
        judge_max(t[root].right);
    }
}

void judge_min(int root){
    if(t[root].left==0&&t[root].right==0){
        return;
    }
    int key=t[root].key;
    if(t[root].left==0){
        if(t[t[root].right].key<key){
            flag2=false;
            return;
        }
    }else if(t[root].right==0){
        if(t[t[root].left].key<key){
            flag2=false;
            return;
        }
    }else{
        if(t[t[root].left].key<key||t[t[root].right].key<key){
            flag2=false;
            return;
        }
    }

    if(t[root].left!=0){
        judge_min(t[root].left);
    }
    if(t[root].right!=0){
        judge_min(t[root].right);
    }

}

void dfs(int root){
    path.push_back(t[root].key);
    if(t[root].left==0&&t[root].right==0){
        for(int i=0;i<path.size();i++){
            cout<<path[i];
            if(i!=path.size()-1){
                cout<<" ";
            }
        }
        cout<<endl;
        path.pop_back();
    }
    if(t[root].right!=0){
        dfs(t[root].right);
    }
    if(t[root].left!=0){
        dfs(t[root].left);
        path.pop_back();
    }
}

int main(){
    cin>>n;
    t.resize(n);

    for(int i=0;i<n;i++){
        cin>>t[i].key;
    }

    for(int i=0;i<n;i++){
        if(i*2+1<n){
            t[i].left=i*2+1;
        }
        if(i*2+2<n){
            t[i].right=i*2+2;
        }
    }

    judge_max(0);
    judge_min(0);

    dfs(0);

    if(flag1){
        cout<<"Max Heap";
    }else if(flag2){
        cout<<"Min Heap";
    }else{
        cout<<"Not Heap";
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值