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.
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>usingnamespacestd;classNode{public:intkey;Node*left;Node*right;Node(intk){key=k;left=nullptr;right=nullptr;}};// This function counts the// number of nodes in a binary tree intcountNodes(Node*root){if(root==nullptr)return0;return1+countNodes(root->left)+countNodes(root->right);}// This function checks if the// binary tree is complete or not boolisCompleteUtil(Node*root,intindex,intnumberOfNodes){if(root==nullptr)returntrue;// If index assigned to current node is more than // number of nodes in the tree,// then the tree is not completeif(index>=numberOfNodes)returnfalse;// Recur for left and right subtreesreturnisCompleteUtil(root->left,2*index+1,numberOfNodes)&&isCompleteUtil(root->right,2*index+2,numberOfNodes);}// This function checks the heap property in the tree.boolisHeapUtil(Node*root){if(root->left==nullptr&&root->right==nullptr)returntrue;// Node will be in the second-last levelif(root->right==nullptr){// Check heap property at the node// No recursive call because no need to// check the last levelreturnroot->key>=root->left->key;}else{// Check heap property at the node and recursively // check the heap property// at left and right subtreesif(root->key>=root->left->key&&root->key>=root->right->key)returnisHeapUtil(root->left)&&isHeapUtil(root->right);elsereturnfalse;}}// Function to check if the binary tree is// a Heap or not.boolisHeap(Node*root){intnodeCount=countNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}intmain(){// Construct the Binary Tree// 10// / \ // 9 8// / \ / \ // 7 6 5 4Node*root=newNode(10);root->left=newNode(9);root->right=newNode(8);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);if(isHeap(root)){cout<<"true";}elsecout<<"false";return0;}
C
// C Program to Check if a given// Binary Tree is a Heap#include<stdio.h>#include<stdlib.h>structNode{intkey;structNode*left;structNode*right;};// Function to count the number of nodes in the binary treeintcountNodes(structNode*root){if(root==NULL)return0;return1+countNodes(root->left)+countNodes(root->right);}// Function to check if the binary tree is complete or notintisCompleteUtil(structNode*root,intindex,intnumberOfNodes){if(root==NULL)return1;// If index assigned to current node is more than // number of nodes in the tree, then the tree is not completeif(index>=numberOfNodes)return0;// Recur for left and right subtreesreturnisCompleteUtil(root->left,2*index+1,numberOfNodes)&&isCompleteUtil(root->right,2*index+2,numberOfNodes);}// Function to check the heap property in the treeintisHeapUtil(structNode*root){// If the node is a leafif(root->left==NULL&&root->right==NULL)return1;// If there is no right child, check heap property for left childif(root->right==NULL){returnroot->key>=root->left->key;}else{// Check heap property at the node and recursively check// the heap property at left and right subtreesif(root->key>=root->left->key&&root->key>=root->right->key)returnisHeapUtil(root->left)&&isHeapUtil(root->right);elsereturn0;}}// Function to check if the binary tree is a heap or notintisHeap(structNode*root){intnodeCount=countNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))return1;return0;}structNode*createNode(intkey){structNode*node=(structNode*)malloc(sizeof(structNode));node->key=key;node->left=NULL;node->right=NULL;returnnode;}intmain(){// Construct the Binary Tree// 10// / \ // 9 8// / \ / \ // 7 6 5 4structNode*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");}elseprintf("false");return0;}
Java
// Java Program to Check if a given Binary// Tree is a HeapclassNode{intkey;Nodeleft;Noderight;Node(intk){key=k;left=null;right=null;}}classGfG{// This function counts the number of nodes // in a binary tree staticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}// This function checks if the binary tree is complete or not staticbooleanisCompleteUtil(Noderoot,intindex,intnumberOfNodes){if(root==null)returntrue;// If index assigned to current node is more than // number of nodes in the tree, then the tree is not completeif(index>=numberOfNodes)returnfalse;// Recur for left and right subtreesreturnisCompleteUtil(root.left,2*index+1,numberOfNodes)&&isCompleteUtil(root.right,2*index+2,numberOfNodes);}// This function checks the heap property in the tree.staticbooleanisHeapUtil(Noderoot){if(root.left==null&&root.right==null)returntrue;// Node will be in the second-last levelif(root.right==null){// Check heap property at the node// No recursive call because no need to // check the last levelreturnroot.key>=root.left.key;}else{// Check heap property at the node and recursively // check the heap property at left and right subtreesif(root.key>=root.left.key&&root.key>=root.right.key)returnisHeapUtil(root.left)&&isHeapUtil(root.right);elsereturnfalse;}}// Function to check if the binary tree is a Heap or not.staticbooleanisHeap(Noderoot){intnodeCount=countNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}publicstaticvoidmain(String[]args){// Construct the Binary Tree// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(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 HeapclassNode:def__init__(self,k):self.key=kself.left=Noneself.right=None# This function counts the number of nodes # in a binary tree defcountNodes(root):ifrootisNone:return0return1+countNodes(root.left)+countNodes(root.right)# This function checks if the binary tree is # complete or not defisCompleteUtil(root,index,numberOfNodes):ifrootisNone:returnTrue# If index assigned to current node is more than # number of nodes in the tree, then the tree is not completeifindex>=numberOfNodes:returnFalse# Recur for left and right subtreesreturnisCompleteUtil(root.left,2*index+1,numberOfNodes)and \
isCompleteUtil(root.right,2*index+2,numberOfNodes)# This function checks the heap property in the tree.defisHeapUtil(root):ifroot.leftisNoneandroot.rightisNone:returnTrue# Node will be in the second-last levelifroot.rightisNone:# Check heap property at the node# No recursive call because no need to check the last levelreturnroot.key>=root.left.keyelse:# Check heap property at the node and recursively # check the heap property at left and right subtreesifroot.key>=root.left.keyandroot.key>=root.right.key:returnisHeapUtil(root.left)andisHeapUtil(root.right)else:returnFalse# Function to check if the binary tree is # a Heap or not.defisHeap(root):nodeCount=countNodes(root)index=0ifisCompleteUtil(root,index,nodeCount) \
andisHeapUtil(root):returnTruereturnFalse# Construct the Binary Tree# 10# / \# 9 8# / \ / \# 7 6 5 4root=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)ifisHeap(root):print("true")else:print("false")
C#
// C# Program to Check if a given Binary // Tree is a HeapusingSystem;classNode{publicintKey;publicNodeLeft;publicNodeRight;publicNode(intk){Key=k;Left=null;Right=null;}}classGfG{// This function counts the number of// nodes in a binary tree staticintCountNodes(Noderoot){if(root==null)return0;return1+CountNodes(root.Left)+CountNodes(root.Right);}// This function checks if the binary tree is// complete or not staticboolisCompleteUtil(Noderoot,intindex,intnumberOfNodes){if(root==null)returntrue;// If index assigned to current node is more than // number of nodes in the tree, then the tree is not completeif(index>=numberOfNodes)returnfalse;// Recur for left and right subtreesreturnisCompleteUtil(root.Left,2*index+1,numberOfNodes)&&isCompleteUtil(root.Right,2*index+2,numberOfNodes);}// This function checks the heap property in the tree.staticboolisHeapUtil(Noderoot){if(root.Left==null&&root.Right==null)returntrue;// Node will be in the second-last levelif(root.Right==null){// Check heap property at the node// No recursive call because no need to check the last levelreturnroot.Key>=root.Left.Key;}else{// Check heap property at the node and recursively // check the heap property at left and right subtreesif(root.Key>=root.Left.Key&&root.Key>=root.Right.Key)returnisHeapUtil(root.Left)&&isHeapUtil(root.Right);elsereturnfalse;}}// Function to check if the binary tree is a Heap or not.staticboolisHeap(Noderoot){intnodeCount=CountNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}staticvoidMain(string[]args){// Construct the Binary Tree// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.Left=newNode(9);root.Right=newNode(8);root.Left.Left=newNode(7);root.Left.Right=newNode(6);root.Right.Left=newNode(5);root.Right.Right=newNode(4);if(isHeap(root)){Console.WriteLine("true");}else{Console.WriteLine("false");}}}
JavaScript
// JavaScript Program to Check if a given // Binary Tree is a HeapclassNode{constructor(k){this.key=k;this.left=null;this.right=null;}}// This function counts the number of nodes// in a binary tree functioncountNodes(root){if(root===null)return0;return1+countNodes(root.left)+countNodes(root.right);}// This function checks if the binary tree is complete or not functionisCompleteUtil(root,index,numberOfNodes){if(root===null)returntrue;// If index assigned to current node is more than // number of nodes in the tree, then the tree is not completeif(index>=numberOfNodes)returnfalse;// Recur for left and right subtreesreturnisCompleteUtil(root.left,2*index+1,numberOfNodes)&&isCompleteUtil(root.right,2*index+2,numberOfNodes);}// This function checks the heap property in the tree.functionisHeapUtil(root){if(root.left===null&&root.right===null)returntrue;// Node will be in the second-last levelif(root.right===null){// Check heap property at the node// No recursive call because no need to check the last levelreturnroot.key>=root.left.key;}else{// Check heap property at the node and recursively // check the heap property at left and right subtreesif(root.key>=root.left.key&&root.key>=root.right.key)returnisHeapUtil(root.left)&&isHeapUtil(root.right);elsereturnfalse;}}// Function to check if the binary tree is a Heap or not.functionisHeap(root){constnodeCount=countNodes(root);constindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}// Driver Code // Construct the Binary Tree// 10// / \// 9 8// / \ / \// 7 6 5 4constroot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);if(isHeap(root)){console.log("true");}else{console.log("false");}
Output
true
[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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to check if the binary tree is a max heapboolisHeap(Node*root){boolresult=true;if(root!=nullptr&&root->left==nullptr&&root->right!=nullptr){returnfalse;}// Check if child is greater than parentif(root!=nullptr&&(root->left!=nullptr&&root->left->data>root->data)||(root->right!=nullptr&&root->right->data>root->data)){returnfalse;}// Check if left subtree has children but right is nullif(root->left!=nullptr){if((root->left->left!=nullptr||root->left->right!=nullptr)&&root->right==nullptr){returnfalse;}}// Check if right subtree has children and // left is nullif(root->right!=nullptr){if((root->right->left!=nullptr||root->right->right!=nullptr)&&root->left==nullptr){returnfalse;}}// Check if right subtree has children but not// left subtreeif(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){returnfalse;}}}}// Recursively call for left and right subtreeif(root!=nullptr&&root->left!=nullptr){boolleft=isHeap(root->left);result=result&left;}if(root!=nullptr&&root->right!=nullptr){boolright=isHeap(root->right);result=result&right;}returnresult;}intmain(){// Binary Tree Representation// 10// / \ // 9 8// / \ / \ // 7 6 5 4Node*root=newNode(10);root->left=newNode(9);root->right=newNode(8);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);if(isHeap(root)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}return0;}
C
// C Program to Check if a given Binary Tree is a Heap#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to check if the binary tree is a max heapintisHeap(structNode*root){intresult=1;if(root!=NULL&&root->left==NULL&&root->right!=NULL){return0;}// Check if child is greater than parentif(root!=NULL&&(root->left!=NULL&&root->left->data>root->data)||(root->right!=NULL&&root->right->data>root->data)){return0;}// Check if left subtree has children but right is nullif(root->left!=NULL){if((root->left->left!=NULL||root->left->right!=NULL)&&root->right==NULL){return0;}}// Check if right subtree has children and left is nullif(root->right!=NULL){if((root->right->left!=NULL||root->right->right!=NULL)&&root->left==NULL){return0;}}// Check if right subtree has children but not left subtreeif(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){return0;}}}}// Recursively call for left and right subtreeif(root!=NULL&&root->left!=NULL){intleft=isHeap(root->left);result=result&&left;}if(root!=NULL&&root->right!=NULL){intright=isHeap(root->right);result=result&&right;}returnresult;}structNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Binary Tree Representation// 10// / \ // 9 8// / \ / \ // 7 6 5 4structNode*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");}return0;}
Java
// Java Program to Check if a given // Binary Tree is a HeapclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}classGfG{// Function to check if the binary tree is a max heapstaticbooleanisHeap(Noderoot){booleanresult=true;if(root!=null&&root.left==null&&root.right!=null){returnfalse;}// Check if child is greater than parentif(root!=null&&(root.left!=null&&root.left.data>root.data)||(root.right!=null&&root.right.data>root.data)){returnfalse;}// Check if left subtree has children but right is nullif(root.left!=null){if((root.left.left!=null||root.left.right!=null)&&root.right==null){returnfalse;}}// Check if right subtree has children and left is nullif(root.right!=null){if((root.right.left!=null||root.right.right!=null)&&root.left==null){returnfalse;}}// Check if right subtree has children but not left subtreeif(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){returnfalse;}}}}// Recursively call for left and right subtreeif(root!=null&&root.left!=null){booleanleft=isHeap(root.left);result=result&&left;}if(root!=null&&root.right!=null){booleanright=isHeap(root.right);result=result&&right;}returnresult;}publicstaticvoidmain(String[]args){// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(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 HeapclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to check if the binary tree is a max heapdefisHeap(root):result=TrueifrootisnotNoneandroot.leftisNoneandroot.rightisnotNone:returnFalse# Check if child is greater than parentifrootisnotNoneand(root.leftisnotNone \
androot.left.data>root.data)or \
(root.rightisnotNoneandroot.right.data>root.data):returnFalse# Check if left subtree has children but right is nullifroot.leftisnotNone:if(root.left.leftisnotNoneorroot.left.rightisnotNone) \
androot.rightisNone:returnFalse# Check if right subtree has children and left is nullifroot.rightisnotNone:if(root.right.leftisnotNoneorroot.right.rightisnotNone) \
androot.leftisNone:returnFalse# Check if right subtree has children but not left subtreeifroot.leftisnotNone:ifroot.left.leftisNoneandroot.left.rightisNone:ifroot.rightisnotNone:ifroot.right.leftisnotNone \
orroot.right.rightisnotNone:returnFalse# Recursively call for left and right subtreeifrootisnotNoneandroot.leftisnotNone:left=isHeap(root.left)result=resultandleftifrootisnotNoneandroot.rightisnotNone:right=isHeap(root.right)result=resultandrightreturnresultif__name__=="__main__":# Binary Tree Representation# 10# / \# 9 8# / \ / \# 7 6 5 4root=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)ifisHeap(root):print("true")else:print("false")
C#
// C# Program to Check if a given Binary // Tree is a HeapusingSystem;classNode{publicintData;publicNodeLeft;publicNodeRight;publicNode(intval){Data=val;Left=null;Right=null;}}classGfG{// Function to check if the binary tree is a max heapstaticboolIsHeap(Noderoot){boolresult=true;if(root!=null&&root.Left==null&&root.Right!=null){returnfalse;}// Check if child is greater than parentif(root!=null&&(root.Left!=null&&root.Left.Data>root.Data)||(root.Right!=null&&root.Right.Data>root.Data)){returnfalse;}// Check if left subtree has children but right is nullif(root.Left!=null){if((root.Left.Left!=null||root.Left.Right!=null)&&root.Right==null){returnfalse;}}// Check if right subtree has children and left is nullif(root.Right!=null){if((root.Right.Left!=null||root.Right.Right!=null)&&root.Left==null){returnfalse;}}// Check if right subtree has children but// not left subtreeif(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){returnfalse;}}}}// Recursively call for left and right subtreeif(root!=null&&root.Left!=null){boolleft=IsHeap(root.Left);result=result&&left;}if(root!=null&&root.Right!=null){boolright=IsHeap(root.Right);result=result&&right;}returnresult;}staticvoidMain(string[]args){// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.Left=newNode(9);root.Right=newNode(8);root.Left.Left=newNode(7);root.Left.Right=newNode(6);root.Right.Left=newNode(5);root.Right.Right=newNode(4);if(IsHeap(root)){Console.WriteLine("true");}else{Console.WriteLine("false");}}}
JavaScript
// JavaScript Program to Check if a given Binary // Tree is a HeapclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to check if the binary tree is a max heapfunctionisHeap(root){letresult=true;if(root!==null&&root.left===null&&root.right!==null){returnfalse;}// Check if child is greater than parentif(root!==null&&(root.left!==null&&root.left.data>root.data)||(root.right!==null&&root.right.data>root.data)){returnfalse;}// Check if left subtree has children but right is nullif(root.left!==null){if((root.left.left!==null||root.left.right!==null)&&root.right===null){returnfalse;}}// Check if right subtree has children and left is nullif(root.right!==null){if((root.right.left!==null||root.right.right!==null)&&root.left===null){returnfalse;}}// Check if right subtree has children but // not left subtreeif(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){returnfalse;}}}}// Recursively call for left and right subtreeif(root!==null&&root.left!==null){letleft=isHeap(root.left);result=result&&left;}if(root!==null&&root.right!==null){letright=isHeap(root.right);result=result&&right;}returnresult;}// Driver Code// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4constroot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);if(isHeap(root)){console.log("true");}else{console.log("false");}
Output
true
[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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intk){data=k;left=nullptr;right=nullptr;}};boolisHeap(Node*root){queue<Node*>q;q.push(root);boolflag=false;while(!q.empty()){Node*temp=q.front();q.pop();if(temp->left){if(flag||temp->left->data>temp->data){returnfalse;}q.push(temp->left);}else{flag=true;}if(temp->right){if(flag||temp->right->data>temp->data){returnfalse;}q.push(temp->right);}else{flag=true;}}returntrue;}intmain(){// Binary Tree Representation// 10// / \ // 9 8// / \ / \ // 7 6 5 4Node*root=newNode(10);root->left=newNode(9);root->right=newNode(8);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);if(isHeap(root)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}return0;}
Java
// Java Program to Check if a given// Binary Tree is a Heapimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft;Noderight;Node(intk){data=k;left=null;right=null;}}classGfG{staticbooleanisHeap(Noderoot){Queue<Node>q=newLinkedList<>();q.add(root);booleanflag=false;while(!q.isEmpty()){Nodetemp=q.poll();if(temp.left!=null){if(flag||temp.left.data>temp.data){returnfalse;}q.add(temp.left);}else{flag=true;}if(temp.right!=null){if(flag||temp.right.data>temp.data){returnfalse;}q.add(temp.right);}else{flag=true;}}returntrue;}publicstaticvoidmain(String[]args){// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);System.out.println(isHeap(root));}}
Python
# Python Program to Check if a given Binary# Tree is a HeapclassNode:def__init__(self,k):self.data=kself.left=Noneself.right=NonedefisHeap(root):queue=[root]flag=Falsewhilequeue:temp=queue.pop(0)iftemp.left:ifflagortemp.left.data>temp.data:returnFalsequeue.append(temp.left)else:flag=Trueiftemp.right:ifflagortemp.right.data>temp.data:returnFalsequeue.append(temp.right)else:flag=TruereturnTrueif__name__=="__main__":# Binary Tree Representation# 10# / \# 9 8# / \ / \# 7 6 5 4root=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 HeapusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intk){data=k;left=null;right=null;}}classGfG{staticboolIsHeap(Noderoot){Queue<Node>q=newQueue<Node>();q.Enqueue(root);boolflag=false;while(q.Count>0){Nodetemp=q.Dequeue();if(temp.left!=null){if(flag||temp.left.data>temp.data){returnfalse;}q.Enqueue(temp.left);}else{flag=true;}if(temp.right!=null){if(flag||temp.right.data>temp.data){returnfalse;}q.Enqueue(temp.right);}else{flag=true;}}returntrue;}staticvoidMain(){// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4Noderoot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);Console.WriteLine(IsHeap(root));}}
JavaScript
// JavaScript Program to Check if a given // Binary Tree is a HeapclassNode{constructor(k){this.data=k;this.left=null;this.right=null;}}functionisHeap(root){constqueue=[root];letflag=false;while(queue.length>0){consttemp=queue.shift();if(temp.left){if(flag||temp.left.data>temp.data){returnfalse;}queue.push(temp.left);}else{flag=true;}if(temp.right){if(flag||temp.right.data>temp.data){returnfalse;}queue.push(temp.right);}else{flag=true;}}returntrue;}// Binary Tree Representation// 10// / \// 9 8// / \ / \// 7 6 5 4constroot=newNode(10);root.left=newNode(9);root.right=newNode(8);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);console.log(isHeap(root));
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.