Given a binary tree, check if it is a min-heap or not. In order words, the binary tree must be a complete binary tree where each node has a higher value than its parent’s value.

For example, the following binary tree is a min-heap:

Min Heap

On the other hand, the following binary tree is not a min-heap:

BST

Practice this problem

1. Recursive Solution

The idea is to traverse the tree in a preorder fashion. The value of each encountered node should be less than its left or right child. If that is not the case for every internal node, the binary tree is not a min-heap.

To check for a complete binary tree, the left and right child’s index for any node is less than the total number of nodes for every node. We can pass the index as a recursion parameter and check for every node that their left and right child’s index is within the correct range.

 
The algorithm can be implemented in a way that both these properties can be checked in a single tree traversal. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The given binary tree is a min-heap

Java


Download  Run Code

Output:

The given binary tree is a min-heap

Python


Download  Run Code

Output:

The given binary tree is a min-heap

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.

2. Iterative Solution

The idea is to perform level order traversal for the given binary tree to check both structural and heap properties of a min-heap.

  1. To check for the structural property, simply check that no non-empty child is encountered for any node once an empty child is seen.
  2. To check for the heap property, check that both left and right children are greater than the parent node. This can be easily done while inserting the children into the queue.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The given binary tree is a min-heap

Java


Download  Run Code

Output:

The given binary tree is a min-heap

Python


Download  Run Code

Output:

The given binary tree is a min-heap

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for level order traversal, where n is the total number of nodes in the binary tree.

 
Exercise: Modify the solution to check the binary tree for max-heap.