Given a binary tree, we need to check it has heap property or not, Binary tree need to fulfill the following two conditions for being a heap –
- It should be a complete tree (i.e. all levels except last should be full).
- Every node’s value should be greater than or equal to its child node (considering max-heap).
For example this tree contains heap property –
While this doesn’t –
We check each of the above condition separately, for checking completeness isComplete and for checking heap isHeapUtil function are written.
Detail about isComplete function can be found here.
isHeapUtil function is written considering the following things –
- Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at most one such node).
- If Node has No child then it’s a leaf node and returns true (Base case)
- If Node has one child (it must be left child because it is a complete tree) then we need to compare this node with its single child only.
- If the Node has both child then check heap property at Node at recur for both subtrees.
Given binary tree is a Heap
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between Binary Heap, Binomial Heap and Fibonacci Heap
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Convert min Heap to max Heap
- Heap Sort for decreasing order using min heap
- Difference between Min Heap and Max Heap
- Tournament Tree (Winner Tree) and Binary Heap
- How to check if a given array represents a Binary Heap?
- Check whether a given binary tree is skewed binary tree or not?
- Height of a complete binary tree (or Heap) with N nodes
- Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Check if the given n-ary tree is a binary tree
- Leftist Tree / Leftist Heap