PAT Heap Paths (30分)

这道题的思路分为三步;

一 根据给出的层序遍历序列建树。

题目中写明是完全二叉树,那么就按照层序遍历的代码,对一些内容进行修改,即可建树,建完后建议写个遍历函数检验一下是否建立对了。

二 写dfs函数从根到叶输出路径

根据输出要求,这种需要设置一个向量vector path,在dfs的过程中向path中添加值,判断到达叶结点时输出路径。

三 判断是最小堆还是最大堆

这里需要设置两个flag,flag1和flag2。有很多方法判断,我图省事,采用的是将向量使用stl库函数sort两遍,一次升序一次降序,观察哪次和原向量相等,然后依据结果设置flag。

具体代码如下:

#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;
struct node{
    int data;
    node* left;
    node* right;
};
int n;
int a[1000];
node* level_order(){
    queue<node*>q;
    node* root=new node;
    root->data=a[0];
    root->left= nullptr;
    root->right= nullptr;
    q.push(root);
    int ind=0;
    while (!q.empty()){
        node* tmp=q.front();
        q.pop();
        ind++;
        if(ind<n){
            node* l=new node;
            l->data=a[ind];
            l->left= nullptr;
            l->right= nullptr;
            tmp->left=l;
            q.push(l);
        }
        ind++;
        if(ind<n){
            node* r=new node;
            r->data=a[ind];
            r->left= nullptr;
            r->right= nullptr;
            tmp->right=r;
            q.push(r);
        }
    }
    return root;
}

vector<int> path;
int flag1=0;
int flag2=0;
void dfs(node* root){
    if(root== nullptr)return;
    if(root->left==nullptr&&root->right== nullptr) {
        if(path.empty())return;
        else{
            path.push_back(root->data);
            for(int i=0;i<path.size();i++){
                cout<<path[i];
                if(i<path.size()-1)cout<<" ";
            }
            vector<int> tmp1=path,tmp2=path;
            sort(tmp1.begin(),tmp1.end());
            sort(tmp2.begin(),tmp2.end(),greater<int>());
            if(tmp1==path){
                flag1=1;
            }
            else if(tmp2==path){
                flag2=1;
            } else{
                flag2=0;
                flag1=0;
            }
            path.pop_back();
            cout<<endl;
            return;
        }
    }
    path.push_back(root->data);
    dfs(root->right);
    dfs(root->left);
    path.pop_back();
}

int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    node* root=level_order();
    dfs(root);
    if(flag1==1&&flag2==0)cout<<"Min Heap";
    else if(flag1==0&&flag2==1)cout<<"Max Heap";
    else cout<<"Not Heap";
    return 0;
}

 

posted @ 2020-09-01 16:14  uy9ko  阅读(104)  评论(0)    收藏  举报