思路:
叶子节点从右到左,入栈到根节点的路径,出栈输出。
1155 Heap Paths (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))
One thing for sure is that all the keys along any path from the root to a leaf in a max/min heap must be in non-increasing/non-decreasing order.
Your job is to check every path in a given complete binary tree, in order to tell if it is a heap or not.
Example:
#include<iostream>
#include<vector>
#include<cmath>
#include<set>
using namespace std;
set<string> heap;
void Print(vector<int> &Tree, int begin, int end)
{
vector<int> Seq;
for(int i = begin; i > end; i--) {
int last = Tree[i];
for(int k = i; k >= 1; k /= 2) {
Seq.push_back(Tree[k]);
int diff = Tree[k] - last;
last = Tree[k];
if(diff > 0) heap.insert("Max Heap");
else if(diff < 0) heap.insert("Min Heap");
}
for(auto x = Seq.rbegin(); x != Seq.rend(); x++) cout << (x == Seq.rbegin()? "" : " ") << *x;
cout << "\n";
Seq.clear();
}
}
int main()
{
int N;
cin >> N;
vector<int> Tree(N+1);
int right = pow(2, (int)log2(N)) - 1;
for(int i = 1; i <= N; i++) cin >> Tree[i];
Print(Tree, right, N/2);
Print(Tree, N, right);
if(heap.size() != 1) cout << "Not Heap";
else cout << *heap.begin();
}