Given the root of a binary tree, determine whether the tree satisfies the heap property.
Binary tree needs to fulfill the following two conditions for being a heap:
It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).
Every node’s value should be greater than or equal to its child node (considering max-heap).
Examples:
Input:
Output: true Explanation : The binary tree is a complete binary tree, and every node’s value is greater than or equal to its children’s values. Therefore, all heap properties are satisfied, and the tree is a valid max-heap.
Input:
Output: false Explanation: Max heap property fails as child node with value 4 is greater than parent node with value 3.
[Approach 1] Using Recursion - O(n) Time and O(h) Space
To check if a binary tree is a max-heap, we need to verify two conditions. First, the tree must be a complete binary tree, This is checked recursively by assigning an index to each node and ensuring no node exceeds the total count. Second, the tree must satisfy the heap property, where every parent node has a value greater than or equal to its children. Using recursion, we compare each node with its children and continue the check for all subtrees. If both conditions hold, the tree is a valid max-heap.
C++
#include<iostream>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intkey;Node*left;Node*right;Node(intk){key=k;left=nullptr;right=nullptr;}};// This function counts the// number of nodes in a binary treeintcountNodes(Node*root){if(root==nullptr)return0;return1+countNodes(root->left)+countNodes(root->right);}// This function checks if the// binary tree is complete or notboolisCompleteUtil(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 recursivelyif(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// 97// / \ // 46 37// / \ / \ // 12 3 7 31// / \ // 6 9Node*root=newNode(97);root->left=newNode(46);root->right=newNode(37);root->left->left=newNode(12);root->left->right=newNode(3);root->right->left=newNode(7);root->right->right=newNode(31);root->left->left->left=newNode(6);root->left->left->right=newNode(9);if(isHeap(root)){cout<<"true";}elsecout<<"false";return0;}
C
#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{intkey;structNode*left;structNode*right;};// Function to create a new NodestructNode*Node_new(intk){structNode*node=(structNode*)malloc(sizeof(structNode));node->key=k;node->left=NULL;node->right=NULL;returnnode;}// This function counts the// number of nodes in a binary treeintcountNodes(structNode*root){if(root==NULL)return0;return1+countNodes(root->left)+countNodes(root->right);}// This function checks 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);}// This function checks the heap property in the tree.intisHeapUtil(structNode*root){if(root->left==NULL&&root->right==NULL)return1;// 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 recursivelyif(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 not.intisHeap(structNode*root){intnodeCount=countNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))return1;return0;}intmain(){// Construct the Binary Tree// 97// / \ // 46 37// / \ / \ // 12 3 7 31// / \ // 6 9structNode*root=Node_new(97);root->left=Node_new(46);root->right=Node_new(37);root->left->left=Node_new(12);root->left->right=Node_new(3);root->right->left=Node_new(7);root->right->right=Node_new(31);root->left->left->left=Node_new(6);root->left->left->right=Node_new(9);if(isHeap(root)){printf("true");}elseprintf("false");return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Node StructureclassNode{intkey;Nodeleft;Noderight;Node(intk){key=k;left=null;right=null;}}// This function counts the// number of nodes in a binary tree classGFG{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 recursivelyif(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// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root)){System.out.println("true");}elseSystem.out.println("false");}}
Python
# Node StructureclassNode:def__init__(self,k):self.key=kself.left=Noneself.right=None# This function counts the# number of nodes in a binary treedefcountNodes(root):ifrootisNone:return0return1+countNodes(root.left)+countNodes(root.right)# This function checks if the# binary tree is complete or notdefisCompleteUtil(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 treedefisHeapUtil(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 recursivelyifroot.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 notdefisHeap(root):nodeCount=countNodes(root)index=0ifisCompleteUtil(root,index,nodeCount)andisHeapUtil(root):returnTruereturnFalseif__name__=="__main__":# Construct the Binary Tree# 97# / \# 46 37# / \ / \# 12 3 7 31# / \# 6 9root=Node(97)root.left=Node(46)root.right=Node(37)root.left.left=Node(12)root.left.right=Node(3)root.right.left=Node(7)root.right.right=Node(31)root.left.left.left=Node(6)root.left.left.right=Node(9)ifisHeap(root):print("true")else:print("false")
C#
usingSystem;// Node StructurepublicclassNode{publicintkey;publicNodeleft;publicNoderight;publicNode(intk){key=k;left=null;right=null;}}publicclassGFG{// This function counts the// number of nodes in a binary treepublicstaticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}// This function checks if the// binary tree is complete or notpublicstaticboolisCompleteUtil(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 treepublicstaticboolisHeapUtil(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 recursivelyif(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 notpublicstaticboolisHeap(Noderoot){intnodeCount=countNodes(root);intindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}publicstaticvoidMain(string[]args){// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Node StructureclassNode{constructor(k){this.key=k;this.left=null;this.right=null;}}// This function counts the// number of nodes in a binary treefunctioncountNodes(root){if(root===null)return0;return1+countNodes(root.left)+countNodes(root.right);}// This function checks if the// binary tree is complete or notfunctionisCompleteUtil(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 treefunctionisHeapUtil(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 recursivelyif(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 notfunctionisHeap(root){constnodeCount=countNodes(root);constindex=0;if(isCompleteUtil(root,index,nodeCount)&&isHeapUtil(root))returntrue;returnfalse;}//Driver Code// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9constroot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root)){console.log("true");}else{console.log("false");}
Output
true
[Approach 2] Single-Pass Recursive Heap Check - O(n) Time and O(h) Space
This approach uses a single recursive function to check whether a binary tree is a max-heap. At each node, it ensures the parent’s value is greater than or equal to its children and simultaneously verifies completeness by checking the node’s position in the tree. Leaf nodes automatically satisfy the heap property, while internal nodes recursively validate their left and right subtrees. If all nodes meet these conditions, the tree is a valid max-heap.
C++
#include<iostream>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Count total nodesintcountNodes(Node*root){if(!root)return0;return1+countNodes(root->left)+countNodes(root->right);}//recursion to check completeness and heapboolisHeap(Node*root,intindex,inttotalNodes){if(!root)returntrue;// Check completenessif(index>=totalNodes)returnfalse;// Check heap propertyif((root->left&&root->left->data>root->data)||(root->right&&root->right->data>root->data))returnfalse;// Recur for left and rightreturnisHeap(root->left,2*index+1,totalNodes)&&isHeap(root->right,2*index+2,totalNodes);}intmain(){// Construct the Binary Tree// 97// / \ // 46 37// / \ / \ // 12 3 7 31// / \ // 6 9Node*root=newNode(97);root->left=newNode(46);root->right=newNode(37);root->left->left=newNode(12);root->left->right=newNode(3);root->right->left=newNode(7);root->right->right=newNode(31);root->left->left->left=newNode(6);root->left->left->right=newNode(9);inttotalNodes=countNodes(root);if(isHeap(root,0,totalNodes))cout<<"true"<<endl;elsecout<<"false"<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{intdata;structNode*left;structNode*right;};structNode*Node_create(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=NULL;node->right=NULL;returnnode;}// Count total nodesintcountNodes(structNode*root){if(!root)return0;return1+countNodes(root->left)+countNodes(root->right);}// recursion to check completeness and heapintisHeap(structNode*root,intindex,inttotalNodes){if(!root)return1;// Check completenessif(index>=totalNodes)return0;// Check heap propertyif((root->left&&root->left->data>root->data)||(root->right&&root->right->data>root->data))return0;// Recur for left and rightreturnisHeap(root->left,2*index+1,totalNodes)&&isHeap(root->right,2*index+2,totalNodes);}intmain(){// Construct the Binary Tree// 97// / \ // 46 37// / \ / \ // 12 3 7 31// / \ // 6 9structNode*root=Node_create(97);root->left=Node_create(46);root->right=Node_create(37);root->left->left=Node_create(12);root->left->right=Node_create(3);root->right->left=Node_create(7);root->right->right=Node_create(31);root->left->left->left=Node_create(6);root->left->left->right=Node_create(9);inttotalNodes=countNodes(root);if(isHeap(root,0,totalNodes))printf("true\n");elseprintf("false\n");return0;}
Java
// Node StructureclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}publicclassGFG{// Count total nodesstaticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}// recursion to check completeness and heapstaticbooleanisHeap(Noderoot,intindex,inttotalNodes){if(root==null)returntrue;// Check completenessif(index>=totalNodes)returnfalse;// Check heap propertyif((root.left!=null&&root.left.data>root.data)||(root.right!=null&&root.right.data>root.data))returnfalse;// Recur for left and rightreturnisHeap(root.left,2*index+1,totalNodes)&&isHeap(root.right,2*index+2,totalNodes);}publicstaticvoidmain(String[]args){// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);inttotalNodes=countNodes(root);if(isHeap(root,0,totalNodes))System.out.println("true");elseSystem.out.println("false");}}
Python
# Node StructureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Count total nodesdefcountNodes(root):ifrootisNone:return0return1+countNodes(root.left)+countNodes(root.right)# recursion to check completeness and heapdefisHeap(root,index,totalNodes):ifrootisNone:returnTrue# Check completenessifindex>=totalNodes:returnFalse# Check heap propertyif(root.leftandroot.left.data>root.data)or \
(root.rightandroot.right.data>root.data):returnFalse# Recur for left and rightreturnisHeap(root.left,2*index+1,totalNodes)and \
isHeap(root.right,2*index+2,totalNodes)if__name__=="__main__":# Construct the Binary Tree# 97# / \# 46 37# / \ / \# 12 3 7 31# / \# 6 9root=Node(97)root.left=Node(46)root.right=Node(37)root.left.left=Node(12)root.left.right=Node(3)root.right.left=Node(7)root.right.right=Node(31)root.left.left.left=Node(6)root.left.left.right=Node(9)totalNodes=countNodes(root)ifisHeap(root,0,totalNodes):print("true")else:print("false")
C#
usingSystem;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGFG{// Count total nodespublicstaticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}// recursion to check completeness and heappublicstaticboolisHeap(Noderoot,intindex,inttotalNodes){if(root==null)returntrue;// Check completenessif(index>=totalNodes)returnfalse;// Check heap propertyif((root.left!=null&&root.left.data>root.data)||(root.right!=null&&root.right.data>root.data))returnfalse;// Recur for left and rightreturnisHeap(root.left,2*index+1,totalNodes)&&isHeap(root.right,2*index+2,totalNodes);}staticvoidMain(string[]args){// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);inttotalNodes=countNodes(root);if(isHeap(root,0,totalNodes))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Count total nodesfunctioncountNodes(root){if(root===null)return0;return1+countNodes(root.left)+countNodes(root.right);}// recursion to check completeness and heapfunctionisHeap(root,index,totalNodes){if(root===null)returntrue;// Check completenessif(index>=totalNodes)returnfalse;// Check heap propertyif((root.left&&root.left.data>root.data)||(root.right&&root.right.data>root.data)){returnfalse;}// Recur for left and rightreturnisHeap(root.left,2*index+1,totalNodes)&&isHeap(root.right,2*index+2,totalNodes);}//Driver Code// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9letroot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);lettotalNodes=countNodes(root);if(isHeap(root,0,totalNodes))console.log("true");elseconsole.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 verify heap properties. Traverse the tree level by level, checking that each node’s value is greater than its children. To keep track of completeness, use a boolean flag variable that becomes true when a node with missing children is encountered; after this point, no node should have any children. If any node violates the heap property or completeness rule, return false. If the entire traversal satisfies both conditions, the tree is a valid max-heap.
C++
#include<iostream>#include<vector>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intk){data=k;left=nullptr;right=nullptr;}};boolisHeap(Node*root){queue<Node*>q;q.push(root);// Flag indicates if a node//with missing children has been seenboolflag=false;while(!q.empty()){Node*temp=q.front();q.pop();// Check left childif(temp->left){// If a node with missing child was seen before // or if left child is bigger than parent, the heap rules are brokenif(flag||temp->left->data>temp->data){returnfalse;}q.push(temp->left);}else{// Left child is missing; set//flag indicating last node encounteredflag=true;}// Check right childif(temp->right){// Same checks as left childif(flag||temp->right->data>temp->data){returnfalse;}q.push(temp->right);}else{// Right child is missing; set flagflag=true;}}returntrue;}intmain(){// Construct the Binary Tree// 97// / \ // 46 37// / \ / \ // 12 3 7 31// / \ // 6 9Node*root=newNode(97);root->left=newNode(46);root->right=newNode(37);root->left->left=newNode(12);root->left->right=newNode(3);root->right->left=newNode(7);root->right->right=newNode(31);root->left->left->left=newNode(6);root->left->left->right=newNode(9);if(isHeap(root)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}return0;}
Java
importjava.util.Queue;importjava.util.LinkedList;// Node StructureclassNode{intdata;Nodeleft;Noderight;Node(intk){data=k;left=null;right=null;}}publicclassGFG{publicstaticbooleanisHeap(Noderoot){Queue<Node>q=newLinkedList<>();q.add(root);// Flag indicates if a node//with missing children has been seenbooleanflag=false;while(!q.isEmpty()){Nodetemp=q.poll();// Check left childif(temp.left!=null){// If a node with missing child was seen before // or if left child is bigger than parent, the heap rules are brokenif(flag||temp.left.data>temp.data){returnfalse;}q.add(temp.left);}else{// Left child is missing; set//flag indicating last node encounteredflag=true;}// Check right childif(temp.right!=null){// Same checks as left childif(flag||temp.right.data>temp.data){returnfalse;}q.add(temp.right);}else{// Right child is missing; set flagflag=true;}}returntrue;}publicstaticvoidmain(String[]args){// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root)){System.out.println("true");}else{System.out.println("false");}}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,k):self.data=kself.left=Noneself.right=NonedefisHeap(root):q=deque()q.append(root)# Flag indicates if a node#with missing children has been seenflag=Falsewhileq:temp=q.popleft()# Check left childiftemp.left:# If a node with missing child was seen before # or if left child is bigger than parent, the heap rules are brokenifflagortemp.left.data>temp.data:returnFalseq.append(temp.left)else:# Left child is missing; set#flag indicating last node encounteredflag=True# Check right childiftemp.right:# Same checks as left childifflagortemp.right.data>temp.data:returnFalseq.append(temp.right)else:# Right child is missing; set flagflag=TruereturnTrueif__name__=="__main__":# Construct the Binary Tree# 97# / \# 46 37# / \ / \# 12 3 7 31# / \# 6 9root=Node(97)root.left=Node(46)root.right=Node(37)root.left.left=Node(12)root.left.right=Node(3)root.right.left=Node(7)root.right.right=Node(31)root.left.left.left=Node(6)root.left.left.right=Node(9)ifisHeap(root):print("true")else:print("false")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intk){data=k;left=null;right=null;}}classGFG{staticboolisHeap(Noderoot){Queue<Node>q=newQueue<Node>();q.Enqueue(root);// Flag indicates if a node//with missing children has been seenboolflag=false;while(q.Count>0){Nodetemp=q.Dequeue();// Check left childif(temp.left!=null){// If a node with missing child was seen before // or if left child is bigger than parent, the heap rules are brokenif(flag||temp.left.data>temp.data){returnfalse;}q.Enqueue(temp.left);}else{// Left child is missing; set//flag indicating last node encounteredflag=true;}// Check right childif(temp.right!=null){// Same checks as left childif(flag||temp.right.data>temp.data){returnfalse;}q.Enqueue(temp.right);}else{// Right child is missing; set flagflag=true;}}returntrue;}staticvoidMain(string[]args){// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9Noderoot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root)){Console.WriteLine("true");}else{Console.WriteLine("false");}}}
JavaScript
// Node StructureclassNode{constructor(k){this.data=k;this.left=null;this.right=null;}}// Custom Queue ImplementationclassQueue{constructor(){this.items=[];this.frontIndex=0;}enqueue(element){this.items.push(element);}dequeue(){if(this.isEmpty())returnnull;returnthis.items[this.frontIndex++];}isEmpty(){returnthis.frontIndex>=this.items.length;}}functionisHeap(root){letq=newQueue();q.enqueue(root);// Flag indicates if a node// with missing children has been seenletflag=false;while(!q.isEmpty()){lettemp=q.dequeue();// Check left childif(temp.left){// If a node with missing child was seen before // or if left child is bigger than parent, the heap rules are brokenif(flag||temp.left.data>temp.data){returnfalse;}q.enqueue(temp.left);}else{// Left child is missing; set// flag indicating last node encounteredflag=true;}// Check right childif(temp.right){// Same checks as left childif(flag||temp.right.data>temp.data){returnfalse;}q.enqueue(temp.right);}else{// Right child is missing; set flagflag=true;}}returntrue;}// Driver Code// Construct the Binary Tree// 97// / \// 46 37// / \ / \// 12 3 7 31// / \// 6 9letroot=newNode(97);root.left=newNode(46);root.right=newNode(37);root.left.left=newNode(12);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(31);root.left.left.left=newNode(6);root.left.left.right=newNode(9);if(isHeap(root)){console.log("true");}else{console.log("false");}