VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-given-binary-tree-is-heap/

⇱ Check if a given Binary Tree is a Heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a given Binary Tree is a Heap

Last Updated : 15 Oct, 2025

Given the root of a binary tree, determine whether the tree satisfies the heap property.

Binary tree needs to fulfill the following two conditions for being a heap:

  • It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).
  • Every node’s value should be greater than or equal to its child node (considering max-heap).

Examples:

Input: 

👁 Check-if-a-given-Binary-Tree-is-a-Heap-

Output: true
Explanation : The binary tree is a complete binary tree, and every node’s value is greater than or equal to its children’s values. Therefore, all heap properties are satisfied, and the tree is a valid max-heap.

Input: 

👁 Check-if-a-given-Binary-Tree-is-a-Heap-2

Output: false
Explanation: Max heap property fails as child node with value 4 is greater than parent node with value 3.

[Approach 1] Using Recursion - O(n) Time and O(h) Space

To check if a binary tree is a max-heap, we need to verify two conditions. First, the tree must be a complete binary tree, This is checked recursively by assigning an index to each node and ensuring no node exceeds the total count. Second, the tree must satisfy the heap property, where every parent node has a value greater than or equal to its children. Using recursion, we compare each node with its children and continue the check for all subtrees. If both conditions hold, the tree is a valid max-heap.


Output
true

[Approach 2] Single-Pass Recursive Heap Check - O(n) Time and O(h) Space

This approach uses a single recursive function to check whether a binary tree is a max-heap. At each node, it ensures the parent’s value is greater than or equal to its children and simultaneously verifies completeness by checking the node’s position in the tree. Leaf nodes automatically satisfy the heap property, while internal nodes recursively validate their left and right subtrees. If all nodes meet these conditions, the tree is a valid max-heap.


Output
true

[Approach 3] Using Level Order Traversal - O(n) Time and O(n) Space

The idea is to use level order traversal to verify heap properties. Traverse the tree level by level, checking that each node’s value is greater than its children. To keep track of completeness, use a boolean flag variable that becomes true when a node with missing children is encountered; after this point, no node should have any children. If any node violates the heap property or completeness rule, return false. If the entire traversal satisfies both conditions, the tree is a valid max-heap.


Output
true
Comment
Article Tags: