Check if a given Binary Tree is a Heap
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfill the following two conditions for being a heap –
- It should be a complete tree (i.e. all levels except the last should be full).
- Every node’s value should be greater than or equal to its child node (considering max-heap).
Examples:
Input:
Output: Given binary tree is a heap
Input:
Output: Given binary tree is not a heap
Check if a given Binary Tree is Heap using Complete Binary Tree
Follow the given steps to solve the problem:
- 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.
Below is the implementation of the above approach:
C++
/* C++ program to checks if a binary tree is max heap or not */ #include <bits/stdc++.h> using namespace std; /* Tree node structure */ struct Node { int key; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node */ struct Node* newNode( int k) { struct Node* node = new Node; node->key = k; node->right = node->left = NULL; return node; } /* This function counts the number of nodes in a binary tree */ unsigned int countNodes( struct 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 */ bool isCompleteUtil( struct Node* root, unsigned int index, unsigned int number_nodes) { // An empty tree is complete if (root == NULL) return ( true ); // If index assigned to // current node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return ( false ); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2 * index + 1, number_nodes) && isCompleteUtil(root->right, 2 * index + 2, number_nodes)); } // This Function checks the // heap property in the tree. bool isHeapUtil( struct Node* root) { // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return ( true ); // node will be in // second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap // property at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return ( false ); } } // Function to check binary // tree is a Heap or Not. bool isHeap( struct Node* root) { // These two are used // in isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true ; return false ; } // Driver's code int main() { struct Node* root = NULL; 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); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << "Given binary tree is a Heap\n" ; else cout << "Given binary tree is not a Heap\n" ; return 0; } // This code is contributed by shubhamsingh10 |
C
/* C program to checks if a binary tree is max heap or not */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> /* Tree node structure */ struct Node { int key; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node */ struct Node* newNode( int k) { struct Node* node = ( struct Node*) malloc ( sizeof ( struct Node)); node->key = k; node->right = node->left = NULL; return node; } /* This function counts the number of nodes in a binary tree */ unsigned int countNodes( struct 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 */ bool isCompleteUtil( struct Node* root, unsigned int index, unsigned int number_nodes) { // An empty tree is complete if (root == NULL) return ( true ); // If index assigned to current // node is more than // number of nodes in tree, // then tree is not complete if (index >= number_nodes) return ( false ); // Recur for left and right subtrees return (isCompleteUtil(root->left, 2 * index + 1, number_nodes) && isCompleteUtil(root->right, 2 * index + 2, number_nodes)); } // This Function checks the // heap property in the tree. bool isHeapUtil( struct Node* root) { // Base case : single // node satisfies property if (root->left == NULL && root->right == NULL) return ( true ); // node will be in second last level if (root->right == NULL) { // check heap property at Node // No recursive call , // because no need to check last level return (root->key >= root->left->key); } else { // Check heap property at Node and // Recursive check heap property // at left and right subtree if (root->key >= root->left->key && root->key >= root->right->key) return ((isHeapUtil(root->left)) && (isHeapUtil(root->right))); else return ( false ); } } // Function to check binary // tree is a Heap or Not. bool isHeap( struct Node* root) { // These two are used in // isCompleteUtil() unsigned int node_count = countNodes(root); unsigned int index = 0; if (isCompleteUtil(root, index, node_count) && isHeapUtil(root)) return true ; return false ; } // Driver's Code int main() { struct Node* root = NULL; 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); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) printf ( "Given binary tree is a Heap\n" ); else printf ( "Given binary tree is not a Heap\n" ); return 0; } |
Java
/* Java program to checks * if a binary tree is max heap or not */ // A Binary Tree node class Node { int key; Node left, right; Node( int k) { key = k; left = right = null ; } } class Is_BinaryTree_MaxHeap { /* This function counts the number of nodes in a binary * tree */ 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 */ boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null ) return true ; // If index assigned to current // node is more than number of // nodes in tree, then tree is // not complete if (index >= number_nodes) return false ; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1 , number_nodes) && isCompleteUtil(root.right, 2 * index + 2 , number_nodes); } // This Function checks // the heap property in the tree. boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null ) return true ; // node will be in second last level if (root.right == null ) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false ; } } // Function to check binary // tree is a Heap or Not. boolean isHeap(Node root) { if (root == null ) return true ; // These two are used // in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0 , node_count) == true && isHeapUtil(root) == true ) return true ; return false ; } // driver function to // test the above functions public static void main(String args[]) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); 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 ); root.left.left.left = new Node( 3 ); root.left.left.right = new Node( 2 ); root.left.right.left = new Node( 1 ); if (bt.isHeap(root) == true ) System.out.println( "Given binary tree is a Heap" ); else System.out.println( "Given binary tree is not a Heap" ); } } // This code has been contributed by Amit Khandelwal |
Python3
# Python3 code To check if a binary # tree is a MAX Heap or not class GFG: def __init__( self , value): self .key = value self .left = None self .right = None def count_nodes( self , root): if root is None : return 0 else : return ( 1 + self .count_nodes(root.left) + self .count_nodes(root.right)) def heap_property_util( self , root): if (root.left is None and root.right is None ): return True if root.right is None : return root.key > = root.left.key else : if (root.key > = root.left.key and root.key > = root.right.key): return ( self .heap_property_util(root.left) and self .heap_property_util(root.right)) else : return False def complete_tree_util( self , root, index, node_count): if root is None : return True if index > = node_count: return False return ( self .complete_tree_util(root.left, 2 * index + 1 , node_count) and self .complete_tree_util(root.right, 2 * index + 2 , node_count)) def check_if_heap( self ): node_count = self .count_nodes( self ) if ( self .complete_tree_util( self , 0 , node_count) and self .heap_property_util( self )): return True else : return False # Driver's Code if __name__ = = '__main__' : root = GFG( 5 ) root.left = GFG( 2 ) root.right = GFG( 3 ) root.left.left = GFG( 1 ) # Function call if root.check_if_heap(): print ( "Given binary tree is a heap" ) else : print ( "Given binary tree is not a Heap" ) # This code has been # contributed by Yash Agrawal |
C#
/* C# program to checks if a binary tree is max heap or not */ using System; // A Binary Tree node public class Node { public int key; public Node left, right; public Node( int k) { key = k; left = right = null ; } } class Is_BinaryTree_MaxHeap { /* This function counts the number of nodes in a binary tree */ 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 */ Boolean isCompleteUtil(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null ) return true ; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false ; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks the // heap property in the tree. Boolean isHeapUtil(Node root) { // Base case : single // node satisfies property if (root.left == null && root.right == null ) return true ; // node will be in second last level if (root.right == null ) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false ; } } // Function to check binary // tree is a Heap or Not. Boolean isHeap(Node root) { if (root == null ) return true ; // These two are used in isCompleteUtil() int node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true ) return true ; return false ; } // Driver's code public static void Main(String[] args) { Is_BinaryTree_MaxHeap bt = new Is_BinaryTree_MaxHeap(); 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); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); // Function call if (bt.isHeap(root) == true ) Console.WriteLine( "Given binary tree is a Heap" ); else Console.WriteLine( "Given binary tree is not a Heap" ); } } // This code has been contributed by Arnab Kundu |
Javascript
/* Javascript program to checks if a binary tree is max heap or not */ // A Binary Tree node 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, number_nodes) { // An empty tree is complete if (root == null ) return true ; // If index assigned to // current node is more than // number of nodes in tree, then // tree is notcomplete if (index >= number_nodes) return false ; // Recur for left and right subtrees return isCompleteUtil(root.left, 2 * index + 1, number_nodes) && isCompleteUtil(root.right, 2 * index + 2, number_nodes); } // This Function checks the // heap property in the tree. function isHeapUtil(root) { // Base case : single // node satisfies property if (root.left == null && root.right == null ) return true ; // node will be in second last level if (root.right == null ) { // check heap property at Node // No recursive call , // because no need to check last level return root.key >= root.left.key; } else { // Check heap property at Node and // Recursive check heap // property at left and // right subtree if (root.key >= root.left.key && root.key >= root.right.key) return isHeapUtil(root.left) && isHeapUtil(root.right); else return false ; } } // Function to check binary // tree is a Heap or Not. function isHeap(root) { if (root == null ) return true ; // These two are used in isCompleteUtil() var node_count = countNodes(root); if (isCompleteUtil(root, 0, node_count) == true && isHeapUtil(root) == true ) return true ; return false ; } // Driver's code var 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); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); // Function call if (isHeap(root) == true ) document.write( "Given binary tree is a Heap" ); else document.write( "Given binary tree is not a Heap" ); // This code is contributed by rrrtnx. |
Given binary tree is a Heap
Time Complexity: O(N), where N is the number of nodes
Auxiliary Space: O(logN), for recursive stack space.
Check if tree is MAX HEAP using complete Binary tree property with SPACE COMPLEXITY O(1)
- Set the initial result to true as if it does not child than it is a heap
- First check if the child is greater than parent, if so return false
- Than check if the left child is null and right child has children or vice-versa, if so return false
- Than 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 AND of result of subtrees
C++
#include <iostream> class Node { public : int data; Node* left; Node* right; Node( int data) { this ->data = data; left = NULL; right = NULL; } }; class IsBinaryTree_MaxHeap { public : bool isHeap(Node* tree) { bool result = true ; // check if child is greater than parent if (tree != NULL && (tree->left != NULL && tree->left->data > tree->data) || (tree->right != NULL && tree->right->data > tree->data)) { return false ; } // check if left subtree has children but right is null if (tree->left != NULL) { if ((tree->left->left != NULL || tree->left->right != NULL) && tree->right == NULL) { return false ; } } // check if right subtree has children and left is null if (tree->right != NULL) { if ((tree->right->left != NULL || tree->right->right != NULL) && tree->left == NULL) { return false ; } } // check if right subtre has children but not left subtree if (tree->left != NULL) { if (tree->left->left == NULL && tree->left->right == NULL) { if (tree->right != NULL) { if (tree->right->left != NULL || tree->right->right != NULL) { return false ; } } } } // recursively call for left and right subtree if (tree != NULL && tree->left != NULL) { bool l = isHeap(tree->left); result = result & l; } if (tree != NULL && tree->right != NULL) { bool r = isHeap(tree->right); result = result & r; } return result; } }; int main() { IsBinaryTree_MaxHeap bt; 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); root->left->left->left = new Node(3); root->left->left->right = new Node(2); root->left->right->left = new Node(1); if (bt.isHeap(root) == true ) std::cout << "Given binary tree is a Heap" << std::endl; else std::cout << "Given binary tree is not a Heap" << std::endl; return 0; } // This code is contributed by vikramshirsath177. |
Java
import java.io.*; import java.util.*; import java.util.LinkedList; import java.util.Queue; class Node { int data; Node left; Node right; Node( int data) { this .data = data; left = null ; right = null ; } } class IsBinaryTree_MaxHeap { // Actual solution/Algorithm boolean isHeap(Node tree) { boolean result = true ; // check if child is greater than parent if (tree != null && (tree.left != null && tree.left.data > tree.data) || (tree.right != null && tree.right.data > tree.data)) { return false ; } // check if left subtree has children but right is // null if (tree.left != null ) { if ((tree.left.left != null || tree.left.right != null ) && tree.right == null ) { return false ; } } // check if right subtree has children and left is // null if (tree.right != null ) { if ((tree.right.left != null || tree.right.right != null ) && tree.left == null ) { return false ; } } // check if right subtre has children but not left // subtree if (tree.left != null ) { if (tree.left.left == null && tree.left.right == null ) { if (tree.right != null ) { if (tree.right.left != null || tree.right.right != null ) { return false ; } } } } // recursively call for left and right subtree if (tree != null && tree.left != null ) { boolean l = isHeap(tree.left); result = result & l; } if (tree != null && tree.right != null ) { boolean r = isHeap(tree.right); result = result & r; } return result; } // This part is where we are taking input and creating // the tree (main class) public static void main(String args[]) { IsBinaryTree_MaxHeap bt = new IsBinaryTree_MaxHeap(); 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 ); root.left.left.left = new Node( 3 ); root.left.left.right = new Node( 2 ); root.left.right.left = new Node( 1 ); if (bt.isHeap(root) == true ) System.out.println( "Given binary tree is a Heap" ); else System.out.println( "Given binary tree is not a Heap" ); } } |
Python3
class Node: def __init__( self , data): self .data = data self .left = None self .right = None class IsBinaryTree_MaxHeap: def isHeap( self , tree): result = True # check if child is greater than parent if tree is not None and (tree.left is not None and tree.left.data > tree.data) or (tree.right is not None and tree.right.data > tree.data): return False # check if left subtree has children but right is None if tree.left is not None : if (tree.left.left is not None or tree.left.right is not None ) and tree.right is None : return False # check if right subtree has children and left is None if tree.right is not None : if (tree.right.left is not None or tree.right.right is not None ) and tree.left is None : return False # check if right subtre has children but not left subtree if tree.left is not None : if tree.left.left is None and tree.left.right is None : if tree.right is not None : if tree.right.left is not None or tree.right.right is not None : return False # recursively call for left and right subtree if tree is not None and tree.left is not None : l = self .isHeap(tree.left) result = result and l if tree is not None and tree.right is not None : r = self .isHeap(tree.right) result = result and r return result def main(): bt = IsBinaryTree_MaxHeap() 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 ) root.left.left.left = Node( 3 ) root.left.left.right = Node( 2 ) root.left.right.left = Node( 1 ) if bt.isHeap(root) = = True : print ( "Given binary tree is a Heap" ) else : print ( "Given binary tree is not a Heap" ) if __name__ = = "__main__" : main() # This code is contributed by vikramshirsath177. |
C#
// C# code for the above approach using System; class Node { public int data; public Node left; public Node right; public Node( int data) { this .data = data; left = null ; right = null ; } } class IsBinaryTree_MaxHeap { // Actual solution/Algorithm bool isHeap(Node tree) { bool result = true ; // check if child is greater than parent if (tree != null && (tree.left != null && tree.left.data > tree.data) || (tree.right != null && tree.right.data > tree.data)) { return false ; } // check if left subtree has children but right is // null if (tree.left != null ) { if ((tree.left.left != null || tree.left.right != null ) && tree.right == null ) { return false ; } } // check if right subtree has children and left is // null if (tree.right != null ) { if ((tree.right.left != null || tree.right.right != null ) && tree.left == null ) { return false ; } } // check if right subtre has children but not left // subtree if (tree.left != null ) { if (tree.left.left == null && tree.left.right == null ) { if (tree.right != null ) { if (tree.right.left != null || tree.right.right != null ) { return false ; } } } } // recursively call for left and right subtree if (tree != null && tree.left != null ) { bool l = isHeap(tree.left); result = result & l; } if (tree != null && tree.right != null ) { bool r = isHeap(tree.right); result = result & r; } return result; } // This part is where we are taking input and creating // the tree (main class) public static void Main( string [] args) { IsBinaryTree_MaxHeap bt = new IsBinaryTree_MaxHeap(); 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); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (bt.isHeap(root) == true ) Console.WriteLine( "Given binary tree is a Heap" ); else Console.WriteLine( "Given binary tree is not a Heap" ); } } // This code is contributed by lokeshpotta20. |
Javascript
class Node { constructor(data) { this .data = data; this .left = null ; this .right = null ; } } class ConvexHull { // Actual solution/Algorithm isHeap(tree) { let result = true ; // check if child is greater than parent if (tree != null && (tree.left != null && tree.left.data > tree.data) || (tree.right != null && tree.right.data > tree.data)) { return false ; } // check if left subtree has children but right is null if (tree.left != null ) { if ((tree.left.left != null || tree.left.right != null ) && tree.right == null ) { return false ; } } // check if right subtree has children and left is null if (tree.right != null ) { if ((tree.right.left != null || tree.right.right != null ) && tree.left == null ) { return false ; } } // check if right subtre has children but not left subtree if (tree.left != null ) { if (tree.left.left == null && tree.left.right == null ) { if (tree.right != null ) { if (tree.right.left != null || tree.right.right != null ) { return false ; } } } } // recursively call for left and right subtree if (tree != null && tree.left != null ) { let l = this .isHeap(tree.left); result = result & l; } if (tree != null && tree.right != null ) { let r = this .isHeap(tree.right); result = result & r; } return result; } } let convexHull = new ConvexHull(); let 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); root.left.left.left = new Node(3); root.left.left.right = new Node(2); root.left.right.left = new Node(1); if (convexHull.isHeap(root) == true ) console.log( "Given binary tree is a Heap" ); else console.log( "Given binary tree is not a Heap" ); // This code is contributed by Shivam Tiwari |
Given binary tree is a Heap
Time Complexity: O(N), where N is the total number of nodes. Auxiliary Space: O(1)
Check if a given Binary Tree is Heap using Level Order Traversal:
Level order traversal can be used 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
Follow the given steps to solve the problem:
- declare a queue for level order traversal and a flag variable nullish equal to false
- Start level order traversal
- Check for the left child of the node and if either the nullish 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 nullish 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 nullish 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 nullish 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 checks if a // binary tree is max heap or not #include <bits/stdc++.h> using namespace std; // Tree node structure struct Node { int data; struct Node* left; struct Node* right; }; // To add a new node struct Node* newNode( int k) { struct Node* node = new Node; node->data = k; node->right = node->left = NULL; return node; } bool isHeap(Node* root) { // Your code here queue<Node*> q; q.push(root); bool nullish = false ; while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left) { if (nullish || temp->left->data > temp->data) { return false ; } q.push(temp->left); } else { nullish = true ; } if (temp->right) { if (nullish || temp->right->data > temp->data) { return false ; } q.push(temp->right); } else { nullish = true ; } } return true ; } // Driver's code int main() { struct Node* root = NULL; 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); root->left->left->left = newNode(3); root->left->left->right = newNode(2); root->left->right->left = newNode(1); // Function call if (isHeap(root)) cout << "Given binary tree is a Heap\n" ; else cout << "Given binary tree is not a Heap\n" ; return 0; } |
Java
// Java program to checks if a // binary tree is max heap or not import java.util.*; class GFG { // Tree node structure static class Node { int data; Node left; Node right; }; // To add a new node static Node newNode( int k) { Node node = new Node(); node.data = k; node.right = node.left = null ; return node; } static boolean isHeap(Node root) { Queue<Node> q = new LinkedList<>(); q.add(root); boolean nullish = false ; while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); if (temp.left != null ) { if (nullish || temp.left.data > temp.data) { return false ; } q.add(temp.left); } else { nullish = true ; } if (temp.right != null ) { if (nullish || temp.right.data > temp.data) { return false ; } q.add(temp.right); } else { nullish = true ; } } return true ; } // Driver's code public static void main(String[] args) { Node root = null ; 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 ); root.left.left.left = newNode( 3 ); root.left.left.right = newNode( 2 ); root.left.right.left = newNode( 1 ); // Function call if (isHeap(root)) System.out.print( "Given binary tree is a Heap\n" ); else System.out.print( "Given binary tree is not a Heap\n" ); } } // This code is contributed by Rajput-Ji |
Python3
# Python3 program to check if a binary tree is max heap or not. from collections import deque class Node: def __init__( self , value): self .key = value self .left = None self .right = None def isHeap(root): queue = deque() queue.append(root) nullish = False while len (queue) > 0 : temp = queue[ 0 ] queue.popleft() if temp.left: if nullish or temp.left.key > temp.key: return False queue.append(temp.left) else : nullish = True if temp.right: if nullish or temp.right.key > temp.key: return False queue.append(temp.right) else : nullish = True return True # Driver's code if __name__ = = '__main__' : 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 ) root.left.left.left = Node( 3 ) root.left.left.right = Node( 2 ) root.left.right.left = Node( 1 ) # Function call if isHeap(root): print ( "Given binary tree is a Heap" ) else : print ( "Given binary tree is not a Heap" ) # This code is contributed by lokeshmvs21. |
C#
// C# program to checks if a // binary tree is max heap or not using System; using System.Collections.Generic; public class GFG { // Tree node structure public class Node { public int data; public Node left; public Node right; }; // To add a new node static Node newNode( int k) { Node node = new Node(); node.data = k; node.right = node.left = null ; return node; } static bool isHeap(Node root) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); bool nullish = false ; while (q.Count != 0) { Node temp = q.Peek(); q.Dequeue(); if (temp.left != null ) { if (nullish || temp.left.data > temp.data) { return false ; } q.Enqueue(temp.left); } else { nullish = true ; } if (temp.right != null ) { if (nullish || temp.right.data > temp.data) { return false ; } q.Enqueue(temp.right); } else { nullish = true ; } } return true ; } // Driver's code public static void Main(String[] args) { Node root = null ; 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); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) Console.Write( "Given binary tree is a Heap\n" ); else Console.Write( "Given binary tree is not a Heap\n" ); } } // This code is contributed by aashish1995 |
Javascript
// JavaScript program to checks if a // binary tree is max heap or not class Node { constructor(data) { this .left = null ; this .right = null ; this .data = data; } } // To add a new node function newNode(k) { let node = new Node(k); return node; } function isHeap(root) { let q = []; q.push(root); let nullish = false ; while (q.length > 0) { let temp = q[0]; q.shift(); if (temp.left != null ) { if (nullish || temp.left.data > temp.data) { return false ; } q.push(temp.left); } else { nullish = true ; } if (temp.right != null ) { if (nullish || temp.right.data > temp.data) { return false ; } q.push(temp.right); } else { nullish = true ; } } return true ; } let root = null ; 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); root.left.left.left = newNode(3); root.left.left.right = newNode(2); root.left.right.left = newNode(1); // Function call if (isHeap(root)) document.write( "Given binary tree is a Heap" + "</br>" ); else document.write( "Given binary tree is not a Heap" + "</br>" ); |
Given binary tree is a Heap
Time Complexity: O(N) where N is the total number of nodes in a given binary tree.
Auxiliary Space: O(N)
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
Please Login to comment...