Traversing the heap PAT Class A 1155 heap path

Link to original title

In computer science, a heap is a specialized tree-based data structure that has heap properties:

If P is the parent node of C, the weight of node P in the big top heap is greater than or equal to the weight of node C, and the weight of node P in the small top heap is less than or equal to the weight of node C value.

A common implementation of a heap is a binary heap, which is implemented by a complete binary tree.

To be sure, in big top/small top heaps, any path from root to leaf must be in non-increasing/non-decreasing order.

Your task is to examine each path in a given complete binary tree to see if it is a heap.

Input Format
The first line contains the integer N, which represents the number of nodes in the tree.

The second line contains N distinct integers representing the sequence of level-order traversals for a given complete binary tree.

Output Format
For a given tree, first output all paths from root to leaves.

Each path occupies one line, and the numbers are separated by spaces. There must be no extra spaces at the beginning and end of the line.

The paths must be output in the following order: for each node in the tree it must be true that paths in its right subtree are output before paths in its left subtree.

In the last line, if it is a large top heap, it will output Max Heap, if it is a small top heap, it will output Min Heap, if it is not a heap, it will output Not Heap.

Data range
1<N≤1000
Input sample 1:
8
98 72 86 60 65 12 23 50
Output sample 1:
98 86 23
98 86 12
98 72 65
98 72 60 50
Max Heap
Input sample 2:
8
8 38 25 58 52 82 70 60
Output example 2:
8 25 70
8 25 82
8 38 52
8 38 58 60
Min Heap
Input example 3:
8
10 28 15 12 34 9 8 56
Output example 3:
10 15 8
10 15 9
10 28 34
10 28 12 56
Not Heap

My solution:

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;

int n;
int a[N];
bool lt, gt;

vector <int> path;
void dfs(int u){
    path.push_back(a[u]);
    if(2 * u > n){
        cout << path[0];
        for(int i = 1; i < path.size(); i ++ ) {
            cout << ' ' << path[i];
            if(path[i] < path[i - 1]) gt = true;
            else if(path[i] > path[i - 1]) lt = true;
        }
        cout << endl;
    }
    if(2 * u + 1 <= n) dfs(2 * u + 1);
    if(2 * u <= n) dfs(2 * u);
    path.pop_back();
}

int main(){
    cin >> n;
    for(int i = 1; i <= n; i ++ ){
        cin >> a[i];
    }
    
    dfs(1);
    
    if(lt && gt) puts("Not Heap");
    else if(lt) puts("Min Heap");
    else puts("Max Heap");
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/126083054