Solution Review: Is Tree a Heap

Let's discuss in detail the solution to find out if the given tree is a min heap or not.

Solution

To see if the given tree is a heap, we need to check the following conditions:

  1. It is a complete tree.
  2. The value of a parent node is smaller than or equal to its left and right child.

We can check these conditions using the following two methods.

First method

The first method is to test if a given tree is complete and if the parent-child property is followed. If a tree is a complete tree and all parent nodes in the tree have a value less than or equal to its children, this tree represents a min heap.

Solution code

Get hands-on with 1400+ tech skills courses.