Check if a given Binary Tree is a Heap
Last Updated :
23 Apr, 2025
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil 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:
Output: True
Input:
Output: False
Explanation: Max heap property fails as node with value 4 is greater than node with value 3.
[Approach 1] Using Complete Binary Tree – O(n) Time and O(h) Space
To determine if a binary tree satisfies heap properties, it must meet two conditions: it should be a complete binary tree, and every node’s key must be greater than or equal to its children’s keys (max heap property). We first check if the tree is complete, and then verify the heap property recursively.
Step By Step Implementation:
- Check each of the above conditions separately, for checking completeness isComplete and for checking heap isHeapUtil functions are written.
- First, check if the given binary tree is complete or not.
- Then to check if the binary tree is a heap or not, check the following points:
- Every Node has 2 children, 0 children (last level nodes), or 1 child (there can be at most one such node).
- If Node has No children then it’s a leaf node and returns true (Base case)
- If Node has one child (it must be the left child because it is a complete tree) then compare this node with its single child only.
- If the Node has both children then check heap property at this Node and recur for both subtrees.
[GFGTABS]
C++
// C++ Program to Check if a given
// Binary Tree is a Heap
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int key;
Node* left;
Node* right;
Node(int k) {
key = k;
left = nullptr;
right = nullptr;
}
};
// This function counts the
// number of nodes in a binary tree
int countNodes(Node* root) {
if (root == nullptr)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
// This function checks if the
// binary tree is complete or not
bool isCompleteUtil(Node* root, int index, int numberOfNodes) {
if (root == nullptr)
return true;
// If index assigned to current node is more than
// number of nodes in the tree,
// then the tree is not complete
if (index >= numberOfNodes)
return false;
// Recur for left and right subtrees
return isCompleteUtil(root->left, 2 * index + 1, numberOfNodes) &&
isCompleteUtil(root->right, 2 * index + 2, numberOfNodes);
}
// This function checks the heap property in the tree.
bool isHeapUtil(Node* root) {
if (root->left == nullptr && root->right == nullptr)
return true;
// Node will be in the second-last level
if (root->right == nullptr) {
// Check heap property at the node
// No recursive call because no need to
// check the last level
return root->key >= root->left->key;
}
else {
// Check heap property at the node and recursively
// check the heap property
// at left and right subtrees
if (root->key >= root->left->key && root->key >= root->right->key)
return isHeapUtil(root->left) && isHeapUtil(root->right);
else
return false;
}
}
// Function to check if the binary tree is
// a Heap or not.
bool isHeap(Node* root) {
int nodeCount = countNodes(root);
int index = 0;
if (isCompleteUtil(root, index, nodeCount) && isHeapUtil(root))
return true;
return false;
}
int main() {
// Construct the Binary Tree
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node* root = new Node(10);
root->left = new Node(9);
root->right = new Node(8);
root->left->left = new Node(7);
root->left->right = new Node(6);
root->right->left = new Node(5);
root->right->right = new Node(4);
if (isHeap(root)) {
cout << "true";
} else cout << "false";
return 0;
}
C
// C Program to Check if a given
// Binary Tree is a Heap
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Function to count the number of nodes in the binary tree
int countNodes(struct Node* root) {
if (root == NULL)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
// Function to check if the binary tree is complete or not
int isCompleteUtil(struct Node* root, int index, int numberOfNodes) {
if (root == NULL)
return 1;
// If index assigned to current node is more than
// number of nodes in the tree, then the tree is not complete
if (index >= numberOfNodes)
return 0;
// Recur for left and right subtrees
return isCompleteUtil(root->left, 2 * index + 1, numberOfNodes) &&
isCompleteUtil(root->right, 2 * index + 2, numberOfNodes);
}
// Function to check the heap property in the tree
int isHeapUtil(struct Node* root) {
// If the node is a leaf
if (root->left == NULL && root->right == NULL)
return 1;
// If there is no right child, check heap property for left child
if (root->right == NULL) {
return root->key >= root->left->key;
} else {
// Check heap property at the node and recursively check
// the heap property at left and right subtrees
if (root->key >= root->left->key && root->key >= root->right->key)
return isHeapUtil(root->left) && isHeapUtil(root->right);
else
return 0;
}
}
// Function to check if the binary tree is a heap or not
int isHeap(struct Node* root) {
int nodeCount = countNodes(root);
int index = 0;
if (isCompleteUtil(root, index, nodeCount) && isHeapUtil(root))
return 1;
return 0;
}
struct Node* createNode(int key) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
// Construct the Binary Tree
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
struct Node* root = createNode(10);
root->left = createNode(9);
root->right = createNode(8);
root->left->left = createNode(7);
root->left->right = createNode(6);
root->right->left = createNode(5);
root->right->right = createNode(4);
if (isHeap(root)) {
printf("true");
} else printf("false");
return 0;
}
Java
// Java Program to Check if a given Binary
// Tree is a Heap
class Node {
int key;
Node left;
Node right;
Node(int k) {
key = k;
left = null;
right = null;
}
}
class GfG {
// This function counts the number of nodes
// in a binary tree
static int countNodes(Node root) {
if (root == null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
// This function checks if the binary tree is complete or not
static boolean isCompleteUtil(Node root, int index, int numberOfNodes) {
if (root == null)
return true;
// If index assigned to current node is more than
// number of nodes in the tree, then the tree is not complete
if (index >= numberOfNodes)
return false;
// Recur for left and right subtrees
return isCompleteUtil(root.left, 2 * index + 1, numberOfNodes) &&
isCompleteUtil(root.right, 2 * index + 2, numberOfNodes);
}
// This function checks the heap property in the tree.
static boolean isHeapUtil(Node root) {
if (root.left == null && root.right == null)
return true;
// Node will be in the second-last level
if (root.right == null) {
// Check heap property at the node
// No recursive call because no need to
// check the last level
return root.key >= root.left.key;
} else {
// Check heap property at the node and recursively
// check the heap property at left and right subtrees
if (root.key >= root.left.key && root.key >= root.right.key)
return isHeapUtil(root.left) && isHeapUtil(root.right);
else
return false;
}
}
// Function to check if the binary tree is a Heap or not.
static boolean isHeap(Node root) {
int nodeCount = countNodes(root);
int index = 0;
if (isCompleteUtil(root, index, nodeCount) && isHeapUtil(root))
return true;
return false;
}
public static void main(String[] args) {
// Construct the Binary Tree
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
if (isHeap(root)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
Python
# Python Program to Check if a given
# Binary Tree is a Heap
class Node:
def __init__(self, k):
self.key = k
self.left = None
self.right = None
# This function counts the number of nodes
# in a binary tree
def countNodes(root):
if root is None:
return 0
return 1 + countNodes(root.left) + countNodes(root.right)
# This function checks if the binary tree is
# complete or not
def isCompleteUtil(root, index, numberOfNodes):
if root is None:
return True
# If index assigned to current node is more than
# number of nodes in the tree, then the tree is not complete
if index >= numberOfNodes:
return False
# Recur for left and right subtrees
return isCompleteUtil(root.left, 2 * index + 1, numberOfNodes) and \
isCompleteUtil(root.right, 2 * index + 2, numberOfNodes)
# This function checks the heap property in the tree.
def isHeapUtil(root):
if root.left is None and root.right is None:
return True
# Node will be in the second-last level
if root.right is None:
# Check heap property at the node
# No recursive call because no need to check the last level
return root.key >= root.left.key
else:
# Check heap property at the node and recursively
# check the heap property at left and right subtrees
if root.key >= root.left.key and root.key >= root.right.key:
return isHeapUtil(root.left) and isHeapUtil(root.right)
else:
return False
# Function to check if the binary tree is
# a Heap or not.
def isHeap(root):
nodeCount = countNodes(root)
index = 0
if isCompleteUtil(root, index, nodeCount) \
and isHeapUtil(root):
return True
return False
# Construct the Binary Tree
# 10
# / \
# 9 8
# / \ / \
# 7 6 5 4
root = Node(10)
root.left = Node(9)
root.right = Node(8)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
if isHeap(root):
print("true")
else:
print("false")
C#
// C# Program to Check if a given Binary
// Tree is a Heap
using System;
class Node {
public int Key;
public Node Left;
public Node Right;
public Node(int k) {
Key = k;
Left = null;
Right = null;
}
}
class GfG {
// This function counts the number of
// nodes in a binary tree
static int CountNodes(Node root) {
if (root == null)
return 0;
return 1 + CountNodes(root.Left) + CountNodes(root.Right);
}
// This function checks if the binary tree is
// complete or not
static bool isCompleteUtil(Node root, int index, int numberOfNodes) {
if (root == null)
return true;
// If index assigned to current node is more than
// number of nodes in the tree, then the tree is not complete
if (index >= numberOfNodes)
return false;
// Recur for left and right subtrees
return isCompleteUtil(root.Left, 2 * index + 1, numberOfNodes) &&
isCompleteUtil(root.Right, 2 * index + 2, numberOfNodes);
}
// This function checks the heap property in the tree.
static bool isHeapUtil(Node root) {
if (root.Left == null && root.Right == null)
return true;
// Node will be in the second-last level
if (root.Right == null) {
// Check heap property at the node
// No recursive call because no need to check the last level
return root.Key >= root.Left.Key;
} else {
// Check heap property at the node and recursively
// check the heap property at left and right subtrees
if (root.Key >= root.Left.Key && root.Key >= root.Right.Key)
return isHeapUtil(root.Left) && isHeapUtil(root.Right);
else
return false;
}
}
// Function to check if the binary tree is a Heap or not.
static bool isHeap(Node root) {
int nodeCount = CountNodes(root);
int index = 0;
if (isCompleteUtil(root, index, nodeCount) && isHeapUtil(root))
return true;
return false;
}
static void Main(string[] args) {
// Construct the Binary Tree
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.Left = new Node(9);
root.Right = new Node(8);
root.Left.Left = new Node(7);
root.Left.Right = new Node(6);
root.Right.Left = new Node(5);
root.Right.Right = new Node(4);
if (isHeap(root)) {
Console.WriteLine("true");
} else {
Console.WriteLine("false");
}
}
}
JavaScript
// JavaScript Program to Check if a given
// Binary Tree is a Heap
class Node {
constructor(k) {
this.key = k;
this.left = null;
this.right = null;
}
}
// This function counts the number of nodes
// in a binary tree
function countNodes(root) {
if (root === null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
// This function checks if the binary tree is complete or not
function isCompleteUtil(root, index, numberOfNodes) {
if (root === null)
return true;
// If index assigned to current node is more than
// number of nodes in the tree, then the tree is not complete
if (index >= numberOfNodes)
return false;
// Recur for left and right subtrees
return isCompleteUtil(root.left, 2 * index + 1, numberOfNodes) &&
isCompleteUtil(root.right, 2 * index + 2, numberOfNodes);
}
// This function checks the heap property in the tree.
function isHeapUtil(root) {
if (root.left === null && root.right === null)
return true;
// Node will be in the second-last level
if (root.right === null) {
// Check heap property at the node
// No recursive call because no need to check the last level
return root.key >= root.left.key;
} else {
// Check heap property at the node and recursively
// check the heap property at left and right subtrees
if (root.key >= root.left.key && root.key >= root.right.key)
return isHeapUtil(root.left) && isHeapUtil(root.right);
else
return false;
}
}
// Function to check if the binary tree is a Heap or not.
function isHeap(root) {
const nodeCount = countNodes(root);
const index = 0;
if (isCompleteUtil(root, index, nodeCount) && isHeapUtil(root))
return true;
return false;
}
// Driver Code
// Construct the Binary Tree
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
const root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
if (isHeap(root)) {
console.log("true");
} else {
console.log("false");
}
[/GFGTABS]
[Approach 2] Using Complete Binary Tree Property – O(n) Time and O(h) Space
To determine if a binary tree satisfies the max heap property, we need to verify two conditions: first, that the binary tree is complete, and second, that each parent node is greater than or equal to its child nodes. We can use a recursive approach to check these conditions for each node in the tree.
Step By Step Implementation :
- First check if the child is greater than parent, if so return false.
- Check if the left child is null and right child has children or vice-versa, if so return false.
- Check if the left child doesn’t have children but right child have children, if so return false.
- Than recursively call for left and right child and return Bitwise AND of result of subtrees
[GFGTABS]
C++
// C++ Program to Check if a given Binary
// Tree is a Heap
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Function to check if the binary tree is a max heap
bool isHeap(Node* root) {
bool result = true;
if (root != nullptr && root->left == nullptr
&& root->right != nullptr) {
return false;
}
// Check if child is greater than parent
if (root != nullptr && (root->left != nullptr &&
root->left->data > root->data) ||
(root->right != nullptr && root->right->data > root->data)) {
return false;
}
// Check if left subtree has children but right is null
if (root->left != nullptr) {
if ((root->left->left != nullptr || root->left->right != nullptr)
&& root->right == nullptr) {
return false;
}
}
// Check if right subtree has children and
// left is null
if (root->right != nullptr) {
if ((root->right->left != nullptr
|| root->right->right != nullptr)
&& root->left == nullptr) {
return false;
}
}
// Check if right subtree has children but not
// left subtree
if (root->left != nullptr) {
if (root->left->left == nullptr
&& root->left->right == nullptr) {
if (root->right != nullptr) {
if (root->right->left != nullptr
|| root->right->right != nullptr) {
return false;
}
}
}
}
// Recursively call for left and right subtree
if (root != nullptr && root->left != nullptr) {
bool left = isHeap(root->left);
result = result & left;
}
if (root != nullptr && root->right != nullptr) {
bool right = isHeap(root->right);
result = result & right;
}
return result;
}
int main() {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node* root = new Node(10);
root->left = new Node(9);
root->right = new Node(8);
root->left->left = new Node(7);
root->left->right = new Node(6);
root->right->left = new Node(5);
root->right->right = new Node(4);
if(isHeap(root)){
cout<<"true"<<endl;
}
else{
cout<<"false"<<endl;
}
return 0;
}
C
// C Program to Check if a given Binary Tree is a Heap
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to check if the binary tree is a max heap
int isHeap(struct Node* root) {
int result = 1;
if (root != NULL && root->left == NULL && root->right != NULL) {
return 0;
}
// Check if child is greater than parent
if (root != NULL && (root->left != NULL
&& root->left->data > root->data) ||
(root->right != NULL && root->right->data > root->data)) {
return 0;
}
// Check if left subtree has children but right is null
if (root->left != NULL) {
if ((root->left->left != NULL || root->left->right != NULL)
&& root->right == NULL) {
return 0;
}
}
// Check if right subtree has children and left is null
if (root->right != NULL) {
if ((root->right->left != NULL || root->right->right != NULL)
&& root->left == NULL) {
return 0;
}
}
// Check if right subtree has children but not left subtree
if (root->left != NULL) {
if (root->left->left == NULL && root->left->right == NULL) {
if (root->right != NULL) {
if (root->right->left != NULL
|| root->right->right != NULL) {
return 0;
}
}
}
}
// Recursively call for left and right subtree
if (root != NULL && root->left != NULL) {
int left = isHeap(root->left);
result = result && left;
}
if (root != NULL && root->right != NULL) {
int right = isHeap(root->right);
result = result && right;
}
return result;
}
struct Node* createNode(int val) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
struct Node* root = createNode(10);
root->left = createNode(9);
root->right = createNode(8);
root->left->left = createNode(7);
root->left->right = createNode(6);
root->right->left = createNode(5);
root->right->right = createNode(4);
if (isHeap(root)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
Java
// Java Program to Check if a given
// Binary Tree is a Heap
class Node {
int data;
Node left;
Node right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to check if the binary tree is a max heap
static boolean isHeap(Node root) {
boolean result = true;
if (root != null && root.left == null && root.right != null) {
return false;
}
// Check if child is greater than parent
if (root != null && (root.left != null
&& root.left.data > root.data) ||
(root.right != null && root.right.data > root.data)) {
return false;
}
// Check if left subtree has children but right is null
if (root.left != null) {
if ((root.left.left != null
|| root.left.right != null) && root.right == null) {
return false;
}
}
// Check if right subtree has children and left is null
if (root.right != null) {
if ((root.right.left != null
|| root.right.right != null) && root.left == null) {
return false;
}
}
// Check if right subtree has children but not left subtree
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
if (root.right != null) {
if (root.right.left != null
|| root.right.right != null) {
return false;
}
}
}
}
// Recursively call for left and right subtree
if (root != null && root.left != null) {
boolean left = isHeap(root.left);
result = result && left;
}
if (root != null && root.right != null) {
boolean right = isHeap(root.right);
result = result && right;
}
return result;
}
public static void main(String[] args) {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
if (isHeap(root)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
Python
# Python Program to Check if a given Binary
# Tree is a Heap
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if the binary tree is a max heap
def isHeap(root):
result = True
if root is not None and root.left is None and root.right is not None:
return False
# Check if child is greater than parent
if root is not None and (root.left is not None \
and root.left.data > root.data) or \
(root.right is not None and root.right.data > root.data):
return False
# Check if left subtree has children but right is null
if root.left is not None:
if (root.left.left is not None or root.left.right is not None) \
and root.right is None:
return False
# Check if right subtree has children and left is null
if root.right is not None:
if (root.right.left is not None or root.right.right is not None) \
and root.left is None:
return False
# Check if right subtree has children but not left subtree
if root.left is not None:
if root.left.left is None and root.left.right is None:
if root.right is not None:
if root.right.left is not None \
or root.right.right is not None:
return False
# Recursively call for left and right subtree
if root is not None and root.left is not None:
left = isHeap(root.left)
result = result and left
if root is not None and root.right is not None:
right = isHeap(root.right)
result = result and right
return result
if __name__ == "__main__":
# Binary Tree Representation
# 10
# / \
# 9 8
# / \ / \
# 7 6 5 4
root = Node(10)
root.left = Node(9)
root.right = Node(8)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
if isHeap(root):
print("true")
else:
print("false")
C#
// C# Program to Check if a given Binary
// Tree is a Heap
using System;
class Node {
public int Data;
public Node Left;
public Node Right;
public Node(int val) {
Data = val;
Left = null;
Right = null;
}
}
class GfG {
// Function to check if the binary tree is a max heap
static bool IsHeap(Node root) {
bool result = true;
if (root != null && root.Left == null
&& root.Right != null) {
return false;
}
// Check if child is greater than parent
if (root != null && (root.Left != null
&& root.Left.Data > root.Data) ||
(root.Right != null && root.Right.Data > root.Data)) {
return false;
}
// Check if left subtree has children but right is null
if (root.Left != null) {
if ((root.Left.Left != null ||
root.Left.Right != null) && root.Right == null) {
return false;
}
}
// Check if right subtree has children and left is null
if (root.Right != null) {
if ((root.Right.Left != null ||
root.Right.Right != null) && root.Left == null) {
return false;
}
}
// Check if right subtree has children but
// not left subtree
if (root.Left != null) {
if (root.Left.Left == null && root.Left.Right == null) {
if (root.Right != null) {
if (root.Right.Left != null
|| root.Right.Right != null) {
return false;
}
}
}
}
// Recursively call for left and right subtree
if (root != null && root.Left != null) {
bool left = IsHeap(root.Left);
result = result && left;
}
if (root != null && root.Right != null) {
bool right = IsHeap(root.Right);
result = result && right;
}
return result;
}
static void Main(string[] args) {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.Left = new Node(9);
root.Right = new Node(8);
root.Left.Left = new Node(7);
root.Left.Right = new Node(6);
root.Right.Left = new Node(5);
root.Right.Right = new Node(4);
if (IsHeap(root)) {
Console.WriteLine("true");
} else {
Console.WriteLine("false");
}
}
}
JavaScript
// JavaScript Program to Check if a given Binary
// Tree is a Heap
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to check if the binary tree is a max heap
function isHeap(root) {
let result = true;
if (root !== null && root.left === null
&& root.right !== null) {
return false;
}
// Check if child is greater than parent
if (root !== null && (root.left !== null
&& root.left.data > root.data) ||
(root.right !== null && root.right.data > root.data)) {
return false;
}
// Check if left subtree has children but right is null
if (root.left !== null) {
if ((root.left.left !== null || root.left.right !== null)
&& root.right === null) {
return false;
}
}
// Check if right subtree has children and left is null
if (root.right !== null) {
if ((root.right.left !== null || root.right.right !== null)
&& root.left === null) {
return false;
}
}
// Check if right subtree has children but
// not left subtree
if (root.left !== null) {
if (root.left.left === null && root.left.right === null) {
if (root.right !== null) {
if (root.right.left !== null
|| root.right.right !== null) {
return false;
}
}
}
}
// Recursively call for left and right subtree
if (root !== null && root.left !== null) {
let left = isHeap(root.left);
result = result && left;
}
if (root !== null && root.right !== null) {
let right = isHeap(root.right);
result = result && right;
}
return result;
}
// Driver Code
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
const root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
if (isHeap(root)) {
console.log("true");
} else {
console.log("false");
}
[/GFGTABS]
[Approach 3] Using Level Order Traversal – O(n) Time and O(n) Space
The idea is to use Level order traversal to check heap properties at each level of the binary tree. Check whether value of each node is greater than the value of its children and keep track of when the last node is encountered and whether it is following the heap properties using a boolean flag.
Step By Step Implementation:
- Declare queue for level order traversal and a flag variable equal to false
- Start level order traversal
- Check for the left child of the node and if either the flag is true or root’s value is less than its left child node, then return false, else push this node into the queue.
- If the node’s left child is null then set flag equal to true, which means we have already encountered the last node, as the node with only zero or one children can occur only once in the complete tree.
- Now check the right child of the node and if either the flag is true or root’s value is less than its right child node, then return false, else push this node into the queue.
- If the node’s right child is null then set flag equal to true, which means we have already encountered the last node, as the node with only zero or one children can occur only once in the complete tree.
- Return true after checking every node in the level order traversal.
[GFGTABS]
C++
// C++ Program to Check if a given Binary
// Tree is a Heap
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int k) {
data = k;
left = nullptr;
right = nullptr;
}
};
bool isHeap(Node* root) {
queue<Node*> q;
q.push(root);
bool flag = false;
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left) {
if (flag || temp->left->data > temp->data) {
return false;
}
q.push(temp->left);
}
else {
flag = true;
}
if (temp->right) {
if (flag || temp->right->data > temp->data) {
return false;
}
q.push(temp->right);
}
else {
flag = true;
}
}
return true;
}
int main() {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node* root = new Node(10);
root->left = new Node(9);
root->right = new Node(8);
root->left->left = new Node(7);
root->left->right = new Node(6);
root->right->left = new Node(5);
root->right->right = new Node(4);
if(isHeap(root)){
cout<<"true"<<endl;
}
else{
cout<<"false"<<endl;
}
return 0;
}
Java
// Java Program to Check if a given
// Binary Tree is a Heap
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left;
Node right;
Node(int k) {
data = k;
left = null;
right = null;
}
}
class GfG {
static boolean isHeap(Node root) {
Queue<Node> q = new LinkedList<>();
q.add(root);
boolean flag = false;
while (!q.isEmpty()) {
Node temp = q.poll();
if (temp.left != null) {
if (flag || temp.left.data > temp.data) {
return false;
}
q.add(temp.left);
} else {
flag = true;
}
if (temp.right != null) {
if (flag || temp.right.data > temp.data) {
return false;
}
q.add(temp.right);
} else {
flag = true;
}
}
return true;
}
public static void main(String[] args) {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
System.out.println(isHeap(root));
}
}
Python
# Python Program to Check if a given Binary
# Tree is a Heap
class Node:
def __init__(self, k):
self.data = k
self.left = None
self.right = None
def isHeap(root):
queue = [root]
flag = False
while queue:
temp = queue.pop(0)
if temp.left:
if flag or temp.left.data > temp.data:
return False
queue.append(temp.left)
else:
flag = True
if temp.right:
if flag or temp.right.data > temp.data:
return False
queue.append(temp.right)
else:
flag = True
return True
if __name__ == "__main__":
# Binary Tree Representation
# 10
# / \
# 9 8
# / \ / \
# 7 6 5 4
root = Node(10)
root.left = Node(9)
root.right = Node(8)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print(isHeap(root))
C#
// C# Program to Check if a given Binary
// Tree is a Heap
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left;
public Node right;
public Node(int k) {
data = k;
left = null;
right = null;
}
}
class GfG {
static bool IsHeap(Node root) {
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
bool flag = false;
while (q.Count > 0) {
Node temp = q.Dequeue();
if (temp.left != null) {
if (flag || temp.left.data > temp.data) {
return false;
}
q.Enqueue(temp.left);
} else {
flag = true;
}
if (temp.right != null) {
if (flag || temp.right.data > temp.data) {
return false;
}
q.Enqueue(temp.right);
} else {
flag = true;
}
}
return true;
}
static void Main() {
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
Node root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
Console.WriteLine(IsHeap(root));
}
}
JavaScript
// JavaScript Program to Check if a given
// Binary Tree is a Heap
class Node {
constructor(k) {
this.data = k;
this.left = null;
this.right = null;
}
}
function isHeap(root) {
const queue = [root];
let flag = false;
while (queue.length > 0) {
const temp = queue.shift();
if (temp.left) {
if (flag || temp.left.data > temp.data) {
return false;
}
queue.push(temp.left);
} else {
flag = true;
}
if (temp.right) {
if (flag || temp.right.data > temp.data) {
return false;
}
queue.push(temp.right);
} else {
flag = true;
}
}
return true;
}
// Binary Tree Representation
// 10
// / \
// 9 8
// / \ / \
// 7 6 5 4
const root = new Node(10);
root.left = new Node(9);
root.right = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
console.log(isHeap(root));
[/GFGTABS]
Similar Reads
Heap Data Structure
A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree. Basic
2 min read
Introduction to Heap - Data Structure and Algorithm Tutorials
A Heap is a special Tree-based Data Structure that has the following properties. It is a Complete Binary Tree.It either follows max heap or min heap property.Max-Heap: The value of the root node must be the greatest among all its descendant nodes and the same thing must be done for its left and righ
15+ min read
Binary Heap
A Binary Heap is a complete binary tree that stores data efficiently, allowing quick access to the maximum or minimum element, depending on the type of heap. It can either be a Min Heap or a Max Heap. In a Min Heap, the key at the root must be the smallest among all the keys in the heap, and this pr
13 min read
Advantages and Disadvantages of Heap
Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
2 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is [Tex]O(n * lg(n)) [/Tex] since each call to Heapify costs [Tex]O(lg(n)) [/Tex]and Build-Heap makes [Tex]O(n) [/Tex]such calls. This upper bound, thou
2 min read
Applications of Heap Data Structure
Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
2 min read
Comparison between Heap and Tree
What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
3 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
4 min read
Easy problems on Heap
Check if a given Binary Tree is a Heap
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil 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 v
15+ min read
How to check if a given array represents a Binary Heap?
Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: ar
11 min read
Iterative HeapSort
HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Find k largest elements in an array
Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17] Table of Content
15+ min read
Kâth Smallest Element in Unsorted Array
Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
15+ min read
Height of a complete binary tree (or Heap) with N nodes
Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
3 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1}Output : arr[] = {10, 5, 3, 1}Input : arr[] = {1, 50, 100, 25}Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Using Min Heap Implementation - O(n Log n) Tim
11 min read