The famous Breadth First Search (BFS) can also be used to check if a tree is a minimum / maximum heap or not.
#include <iostream> #include <queue> int main() { int tree[] = {5, 9, 11, 14, 18, 19, 21, 33, 17, 27}; int size = 10; std::queue <int> q; q.push(0); bool flag = true; while(!q.empty()) { int x = q.front(); q.pop(); int left = 2*x+1, right = 2*x+2; // 0-based indexing used here if(left < size) { // check if left child exists or not. q.push(left); // check value at parent is less than child or not. if(tree[x] > tree[left]) { flag = false; break; } } if(right < size) { // check whether right child exists or not. q.push(right); if(tree[x] > tree[right]) { // check value of parent less than child. flag = false; break; } } } if(flag) std::cout << "It is minimum heap.\n"; else std::cout << "Not a minimum heap.\n"; return 0; }
The idea is similar to the idea of wookie919 .
source share