1147 Heaps (30 point(s))

Ideas:

The type of binary heap can be judged based on the comparison of the size of the parent node and the child node; the post-order traversal can be realized by recursion.

1147 Heaps (30 point(s))

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree. (Quoted from Wikipedia at https://en.wikipedia.org/wiki/Heap_(data_structure))

Your job is to tell if a given complete binary tree is a heap.

Example:

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

string Judge(vector<int> &heap)
{
    set<string> line;
    int N = heap.size() - 1;
    for(int i = 1; i < N; i++) {
        int left = i * 2;
        int right = left + 1;
        if(left <= N) {
            if(heap[left] > heap[i]) line.insert("Min Heap\n");
            else if(heap[left] < heap[i]) line.insert("Max Heap\n");
        }  
        if(right <= N) {
            if(heap[right] > heap[i]) line.insert("Min Heap\n");
            else if(heap[right] < heap[i]) line.insert("Max Heap\n");
        }  
    }
    if(line.size() != 1) return "Not Heap\n";
    else return *line.begin();
}

void postOrder(vector<int> &heap, int root)
{
    int N = heap.size() - 1;
    if(root*2 <= N) postOrder(heap, root*2);
    if(root*2+1 <= N) postOrder(heap, root*2+1);
    cout << heap[root] << (root == 1 ? "" : " ") ;
}

int main()
{
    int  N, M;
    cin >> M >> N;
    for(int i = 0; i < M; i++) {
        vector<int> heap(N+1);
        for(int k = 1; k <= N; k++) cin >> heap[k];
        cout << (i == 0 ? "" : "\n") << Judge(heap);
        postOrder(heap, 1);
    }
}

 

Guess you like

Origin blog.csdn.net/u012571715/article/details/114681809