Check if a given Binary Tree is a Heap
Last Updated :
23 Jul, 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.
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");
}
[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
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");
}
[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.
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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem