Skip to main content

Check whether binary tree is form of min heap

In this problem are determining whether a given binary tree is a valid representation of a min heap. A min heap is a binary tree data structure where each parent node has a value less than or equal to its child nodes. Your task is to check if a given binary tree follows the properties of a min heap.

Problem Statement

Given a binary tree, you need to determine whether the tree represents a valid min heap or not.

Example

Consider the given binary tree:

         1
    /   \
   5     6
  / \    / \
 9   7  8   10
/   /  \     
13  12   11    

In this case, the binary tree is a min heap because each parent node's value is less than or equal to its child nodes' values.

         1
    /   \
   5     6
  / \    / \
 9   7  8   10
/   /  \     \
13  12   11    2

Above tree is not min heap.

Idea to Solve

To determine whether the given binary tree represents a min heap, you need to traverse the tree and check whether the min heap property is satisfied for each parent node and its children.

Pseudocode

function insert(data):
 create new_node
 set new_node's data to data
 set new_node's left and right pointers to NULL
 return new_node

function is_min_heap(root):
 if root is not NULL:
     if (root has left child and root's left child value < root's value) or 
        (root has right child and root's right child value < root's value):
         return false
     
     if is_min_heap(root's left child) and is_min_heap(root's right child):
         return true
     
     return false
     
 return true

function inorder(node):
    if node is not NULL:
        inorder(node's left child)
        print node's data
        inorder(node's right child)

main:
 root = NULL
 root = insert(1)
 # Insert other nodes here
 
 inorder(root)
 if is_min_heap(root):
     print "Min heap Binary Tree"
 else:
     print "Not a Min Heap Binary Tree"

Algorithm Explanation

  1. The insert function creates a new node for the binary tree with the given data value and initializes its left and right pointers.

  2. The is_min_heap function checks whether the given node and its children satisfy the min heap property. If any violation is found, it returns false. It recursively checks the left and right subtrees as well.

  3. The inorder function performs an inorder traversal of the binary tree and prints the node values.

Code Solution

/*
  C Program 
  Check whether binary tree is form of min heap
*/
#include <stdio.h>

#include <stdlib.h>
//structure of Binary Tree node
struct Node
{
  int data;
  struct Node*left,*right;
};


//Create a binary tree nodes and node fields (data,pointer) 
//And returning the reference of newly nodes
struct Node* insert(int data)
{
  //Create dynamic memory to new binary tree node
  struct Node*new_node=(struct Node*)malloc(sizeof(struct Node));
  if(new_node!=NULL){
    //set data and pointer values
    new_node->data=data;
    new_node->left=NULL; //Initially node left-pointer is NULL
    new_node->right=NULL;//Initially node right-pointer is NULL
  }else
  {
    printf("Memory Overflow\n");
    exit(0); //Terminate program execution
  }
  //return reference
  return new_node;
  
}

//Check that given binary tree is form of min heap or not
int is_min_heap(struct Node*root)
{

  if(root!=NULL)
  {
    if(root->left!=NULL && root->left->data < root->data ||
      root->right!=NULL && root->right->data < root->data)

    {
      //When tree is not a min heap
      return 0;
    }

    if(is_min_heap(root->left) && is_min_heap(root->right))
    {
      //When tree is min heap
      return 1;
    }

    return 0;
  }
  
  return 1;

}
//Display tree element inorder form
void inorder(struct Node*node){

  if(node){

    inorder(node->left);
    //Print node value
    printf("  %d",node->data);
    inorder(node->right);
  }
}
int main(){

  struct Node*root=NULL;
 
  /*  
  Make A Binary Tree
  -----------------------
             1
           /   \
          5     6
         / \    / \
        9   7  8   10
       /   /  \     
      13  12   11    
              
            
  */

  //Insertion of binary tree nodes
  root                    =insert(1);
  root->left              =insert(5);
  root->right             =insert(6);
  root->right->right      =insert(10);
  root->right->left       =insert(8);
  root->left->left        =insert(9);
  root->left->left->left  =insert(13);
  root->left->right =insert(7);
  root->left->right->right =insert(11);
  root->left->right->left =insert(12);

  inorder(root);
  if(is_min_heap(root)==1)
  {
    printf("\n Min heap Binary Tree \n");
  }
  else
  {
    printf("\n Not a Min Heap Binary Tree \n");
  }

  /*  
  Make A Binary Tree
  -----------------------
             1
           /   \
          5     6
         / \    / \
        9   7  8   10
       /   /  \     \
      13  12   11    2    
  */
  root->right->right->right = insert(2);
  inorder(root);
  if(is_min_heap(root)==1)
  {
    printf("\n Min heap Binary Tree \n");
  }
  else
  {
    printf("\n Not a Min Heap Binary Tree \n");
  }
  return 0;
}

Output

  13  9  5  12  7  11  1  8  6  10
 Min heap Binary Tree
  13  9  5  12  7  11  1  8  6  10  2
 Not a Min Heap Binary Tree
/*
  C++ Program
  Check whether binary tree is form of min heap
*/
#include<iostream>

using namespace std;


//Structure of Binary Tree node
class Node {
	public:
	int data;
	Node *left;
	Node *right;
	//make a tree node

	Node(int data) {
		//assign field values
		this->data = data;
		this->left = NULL;
		this->right = NULL;
	}
};
class MyHeap {
	public:
		Node *root;
	MyHeap() {
		this->root = NULL;
	}
	//Check that given binary tree is form of min heap or not
	bool is_min_heap(Node *root) {
		if (root != NULL) {
			if (root->left != NULL && root->left->data < root->data || root->right != NULL && root->right->data < root->data) {
				return
				//When tree is not a min heap
				false;
			}
			if (this->is_min_heap(root->left) == true && this->is_min_heap(root->right) == true) {
				return
				//When the tree is in the form of a min heap
				true;
			}
			return false;
		}
		return true;
	}
	//Display tree elements in order form
	void inorder(Node *node) {
		if (node != NULL) {
			this->inorder(node->left);
			//Print node value

			cout << " " << node->data;
			this->inorder(node->right);
		}
	}
};
int main() {
	MyHeap obj = MyHeap();
	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     
	        13  12   11    
	                
	              
	    */
	//Insertion of binary tree nodes
	obj.root = new Node(1);
	obj.root->left = new Node(5);
	obj.root->right = new Node(6);
	obj.root->right->right = new Node(10);
	obj.root->right->left = new Node(8);
	obj.root->left->left = new Node(9);
	obj.root->left->left->left = new Node(13);
	obj.root->left->right = new Node(7);
	obj.root->left->right->right = new Node(11);
	obj.root->left->right->left = new Node(12);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		cout << "\n Min heap Binary Tree \n";
	} else {
		cout << "\n Not a Min Heap Binary Tree \n";
	}
	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     \
	        13  12   11    2    
	    */
	obj.root->right->right->right = new Node(2);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		cout << "\n Min heap Binary Tree \n";
	} else {
		cout << "\n Not a Min Heap Binary Tree \n";
	}
	return 0;
}

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
/*
  Java Program
  Check whether binary tree is form of min heap
*/
//Structure of Binary Tree node
class Node {

  public int data;
  public Node left;
  public Node right;
  //make a tree node
  public Node(int data) {
    //assign field values
    this.data = data;
    left = null;
    right = null;
  }
}
public class MyHeap {

  public Node root;
  public MyHeap() {
    root = null;
  }
  //Check that given binary tree is form of min heap or not
  public boolean is_min_heap(Node root) {

    if (root != null) {
      if (root.left != null && root.left.data < root.data ||
        root.right != null && root.right.data < root.data) {
        //When tree is not a min heap
        return false;
      }

      if (is_min_heap(root.left) == true && is_min_heap(root.right) == true) {
        //When the tree is in the form of a min heap
        return true;
      }

      return false;
    }

    return true;

  }
  //Display tree elements in order form
  public void inorder(Node node) {

    if (node != null) {
      inorder(node.left);
      //Print node value
      System.out.print("  "+ node.data);
      inorder(node.right);
    }

  }
  public static void main(String[] args) {
    MyHeap obj = new MyHeap();
    /* 
    Make A Binary Tree
    -----------------------
               1
             /   \
            5     6
           / \    / \
          9   7  8   10
         /   /  \     
        13  12   11    
                
              
    */

    //Insertion of binary tree nodes
    obj.root = new Node(1);
    obj.root.left = new Node(5);
    obj.root.right = new Node(6);
    obj.root.right.right = new Node(10);
    obj.root.right.left = new Node(8);
    obj.root.left.left = new Node(9);
    obj.root.left.left.left = new Node(13);
    obj.root.left.right = new Node(7);
    obj.root.left.right.right = new Node(11);
    obj.root.left.right.left = new Node(12);

    obj.inorder(obj.root);
    if (obj.is_min_heap(obj.root) == true) {
      System.out.print("\n Min heap Binary Tree \n");
    } else {
      System.out.print("\n Not a Min Heap Binary Tree \n");
    }

    /* 
    Make A Binary Tree
    -----------------------
               1
             /   \
            5     6
           / \    / \
          9   7  8   10
         /   /  \     \
        13  12   11    2    
    */
    obj.root.right.right.right = new Node(2);
    obj.inorder(obj.root);
    if (obj.is_min_heap(obj.root) == true) {
      System.out.print("\n Min heap Binary Tree \n");
    } else {
      System.out.print("\n Not a Min Heap Binary Tree \n");
    }
  }
}

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
/*
  C# Program
  Check whether binary tree is form of min heap
*/
using System;


//Structure of Binary Tree node
public class Node {
	public int data;
	public Node left;
	public Node right;
	//make a tree node
	public Node(int data) {
		//assign field values
		this.data = data;
		left = null;
		right = null;
	}
}
public class MyHeap {
	public Node root;
	public MyHeap() {
		root = null;
	}
	//Check that given binary tree is form of min heap or not
	public Boolean is_min_heap(Node root) {
		if (root != null) {
			if (root.left != null && root.left.data < root.data || root.right != null && root.right.data < root.data) {
				return false;
			}
			if (is_min_heap(root.left) == true && is_min_heap(root.right) == true) {
				return true;
			}
			return false;
		}
		return true;
	}
	//Display tree elements in order form
	public void inorder(Node node) {
		if (node != null) {
			inorder(node.left);
			Console.Write(" " + node.data);
			inorder(node.right);
		}
	}
	public static void Main(String[] args) {
		MyHeap obj = new MyHeap();
		/* 
		    Make A Binary Tree
		    -----------------------
		               1
		             /   \
		            5     6
		           / \    / \
		          9   7  8   10
		         /   /  \     
		        13  12   11    
		                
		              
		    */
		//Insertion of binary tree nodes
		obj.root = new Node(1);
		obj.root.left = new Node(5);
		obj.root.right = new Node(6);
		obj.root.right.right = new Node(10);
		obj.root.right.left = new Node(8);
		obj.root.left.left = new Node(9);
		obj.root.left.left.left = new Node(13);
		obj.root.left.right = new Node(7);
		obj.root.left.right.right = new Node(11);
		obj.root.left.right.left = new Node(12);
		obj.inorder(obj.root);
		if (obj.is_min_heap(obj.root) == true) {
			Console.Write("\n Min heap Binary Tree \n");
		} else {
			Console.Write("\n Not a Min Heap Binary Tree \n");
		}
		/* 
		    Make A Binary Tree
		    -----------------------
		               1
		             /   \
		            5     6
		           / \    / \
		          9   7  8   10
		         /   /  \     \
		        13  12   11    2    
		    */
		obj.root.right.right.right = new Node(2);
		obj.inorder(obj.root);
		if (obj.is_min_heap(obj.root) == true) {
			Console.Write("\n Min heap Binary Tree \n");
		} else {
			Console.Write("\n Not a Min Heap Binary Tree \n");
		}
	}
}

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
<?php
/*
  Php Program
  Check whether binary tree is form of min heap
*/
//Structure of Binary Tree node
class Node {
	public $data;
	public $left;
	public $right;
	//make a tree node

	function __construct($data) {
		//assign field values
		$this->data = $data;
		$this->left = null;
		$this->right = null;
	}
}
class MyHeap {
	public $root;

	function __construct() {
		$this->root = null;
	}
	//Check that given binary tree is form of min heap or not

	public 	function is_min_heap($root) {
		if ($root != null) {
			if ($root->left != null && $root->left->data < $root->data || $root->right != null && $root->right->data < $root->data) {
				return false;
			}
			if ($this->is_min_heap($root->left) == true && $this->is_min_heap($root->right) == true) {
				return true;
			}
			return false;
		}
		return true;
	}
	//Display tree elements in order form

	public 	function inorder($node) {
		if ($node != null) {
			$this->inorder($node->left);
			//Print node value

			echo(" ". $node->data);
			$this->inorder($node->right);
		}
	}
}

function main() {
	$obj = new MyHeap();
	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     
	        13  12   11    
	                
	              
	    */
	//Insertion of binary tree nodes
	$obj->root = new Node(1);
	$obj->root->left = new Node(5);
	$obj->root->right = new Node(6);
	$obj->root->right->right = new Node(10);
	$obj->root->right->left = new Node(8);
	$obj->root->left->left = new Node(9);
	$obj->root->left->left->left = new Node(13);
	$obj->root->left->right = new Node(7);
	$obj->root->left->right->right = new Node(11);
	$obj->root->left->right->left = new Node(12);
	$obj->inorder($obj->root);
	if (
		$obj->is_min_heap($obj->root) == true) {
		echo("\n Min heap Binary Tree \n");
	} else {
		echo("\n Not a Min Heap Binary Tree \n");
	}
	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     \
	        13  12   11    2    
	    */
	$obj->root->right->right->right = new Node(2);
	$obj->inorder($obj->root);
	if (
		$obj->is_min_heap($obj->root) == true) {
		echo("\n Min heap Binary Tree \n");
	} else {
		echo("\n Not a Min Heap Binary Tree \n");
	}

}
main();

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
/*
  Node Js Program
  Check whether binary tree is form of min heap
*/
//Structure of Binary Tree node
class Node {
	//make a tree node

	constructor(data) {
		//assign field values
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
class MyHeap {
	constructor() {
		this.root = null;
	}

	//Check that given binary tree is form of min heap or not
	is_min_heap(root) {
		if (root != null) {
			if (root.left != null && root.left.data < root.data || root.right != null && root.right.data < root.data) {
				return false;
			}

			if (this.is_min_heap(root.left) == true && this.is_min_heap(root.right) == true) {
				return true;
			}

			return false;
		}

		return true;
	}

	//Display tree elements in order form
	inorder(node) {
		if (node != null) {
			this.inorder(node.left);
			//Print node value

			process.stdout.write(" " + node.data);
			this.inorder(node.right);
		}
	}
}

function main(args) {
	var obj = new MyHeap();
	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     
	        13  12   11    
	                
	              
	    */
	//Insertion of binary tree nodes
	obj.root = new Node(1);
	obj.root.left = new Node(5);
	obj.root.right = new Node(6);
	obj.root.right.right = new Node(10);
	obj.root.right.left = new Node(8);
	obj.root.left.left = new Node(9);
	obj.root.left.left.left = new Node(13);
	obj.root.left.right = new Node(7);
	obj.root.left.right.right = new Node(11);
	obj.root.left.right.left = new Node(12);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		process.stdout.write("\n Min heap Binary Tree \n");
	} else {
		process.stdout.write("\n Not a Min Heap Binary Tree \n");
	}

	/*
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     \
	        13  12   11    2    
	    */
	obj.root.right.right.right = new Node(2);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		process.stdout.write("\n Min heap Binary Tree \n");
	} else {
		process.stdout.write("\n Not a Min Heap Binary Tree \n");
	}
}

main();

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
# Python 3 Program
# Check whether binary tree is form of min heap

# Structure of Binary Tree node
class Node :
	
	 # make a tree node
	def __init__(self, data) :
		 # assign field values
		self.data = data
		self.left = None
		self.right = None
	

class MyHeap :
	
	def __init__(self) :
		self.root = None
	
	 # Check that given binary tree is form of min heap or not
	def is_min_heap(self, root) :
		if (root != None) :
			if (root.left != None and root.left.data < root.data or 
                root.right != None and root.right.data < root.data) :
				return False
			
			if (self.is_min_heap(root.left) == True and 
                self.is_min_heap(root.right) == True) :
				return True
			
			return False
		
		return True
	
	 # Display tree elements in order form
	def inorder(self, node) :
		if (node != None) :
			self.inorder(node.left)
			print(" ", node.data, end = "")
			self.inorder(node.right)
		
	

def main() :
	obj = MyHeap()
	 
	#     Make A Binary Tree
	#     -----------------------
	#                1
	#              /   \
	#             5     6
	#            / \    / \
	#           9   7  8   10
	#          /   /  \     
	#         13  12   11    
	#                 
	#               
	#     
	 # Insertion of binary tree nodes
	obj.root = Node(1)
	obj.root.left = Node(5)
	obj.root.right = Node(6)
	obj.root.right.right = Node(10)
	obj.root.right.left = Node(8)
	obj.root.left.left = Node(9)
	obj.root.left.left.left = Node(13)
	obj.root.left.right = Node(7)
	obj.root.left.right.right = Node(11)
	obj.root.left.right.left = Node(12)
	obj.inorder(obj.root)
	if (obj.is_min_heap(obj.root) == True) :
		print("\n Min heap Binary Tree \n", end = "")
	else :
		print("\n Not a Min Heap Binary Tree \n", end = "")
	
	 
	#     Make A Binary Tree
	#     -----------------------
	#                1
	#              /   \
	#             5     6
	#            / \    / \
	#           9   7  8   10
	#          /   /  \     \
	#         13  12   11    2    
	#     
	obj.root.right.right.right = Node(2)
	obj.inorder(obj.root)
	if (obj.is_min_heap(obj.root) == True) :
		print("\n Min heap Binary Tree \n", end = "")
	else :
		print("\n Not a Min Heap Binary Tree \n", end = "")
	


if __name__ == "__main__":
	main()

Output

  13  9  5  12  7  11  1  8  6  10
 Min heap Binary Tree
  13  9  5  12  7  11  1  8  6  10  2
 Not a Min Heap Binary Tree
#   Ruby Program
#   Check whether binary tree is form of min heap
 # Structure of Binary Tree node
class Node 
	# Define the accessor and reader of class Node
    attr_reader :data, :left, :right
    attr_accessor :data, :left, :right
	# make a tree node
	def initialize(data) 
		 # assign field values
		self.data = data
		@left = nil
		@right = nil
	end
end

class MyHeap 
	# Define the accessor and reader of class MyHeap
    attr_reader :root
    attr_accessor :root
	def initialize() 
		@root = nil
	end
	 # Check that given binary tree is form of min heap or not
	def is_min_heap(root) 
		if (root != nil) 
			if (root.left != nil && root.left.data < root.data || root.right != nil && root.right.data < root.data) 
				return false
			end
			if (self.is_min_heap(root.left) == true && self.is_min_heap(root.right) == true) 
				return true
			end
			return false
		end
		return true
	end
	 # Display tree elements in order form
	def inorder(node) 
		if (node != nil) 
			self.inorder(node.left)
			 # Print node value

			print(" ", node.data)
			self.inorder(node.right)
		end
	end
end
def main() 
	obj = MyHeap.new()
	 
	#     Make A Binary Tree
	#     -----------------------
	#                1
	#              /   \
	#             5     6
	#            / \    / \
	#           9   7  8   10
	#          /   /  \     
	#         13  12   11    
	#                 
	#               
	#     
	 # Insertion of binary tree nodes
	obj.root = Node.new(1)
	obj.root.left = Node.new(5)
	obj.root.right = Node.new(6)
	obj.root.right.right = Node.new(10)
	obj.root.right.left = Node.new(8)
	obj.root.left.left = Node.new(9)
	obj.root.left.left.left = Node.new(13)
	obj.root.left.right = Node.new(7)
	obj.root.left.right.right = Node.new(11)
	obj.root.left.right.left = Node.new(12)
	obj.inorder(obj.root)
	if (obj.is_min_heap(obj.root) == true) 
		print("\n Min heap Binary Tree \n")
	else 
		print("\n Not a Min Heap Binary Tree \n")
	end
	 
	#     Make A Binary Tree
	#     -----------------------
	#                1
	#              /   \
	#             5     6
	#            / \    / \
	#           9   7  8   10
	#          /   /  \     \
	#         13  12   11    2    
	#     
	obj.root.right.right.right = Node.new(2)
	obj.inorder(obj.root)
	if (obj.is_min_heap(obj.root) == true) 
		print("\n Min heap Binary Tree \n")
	else 
		print("\n Not a Min Heap Binary Tree \n")
	end
end


main()

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree 
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree 
/*
  Scala Program
  Check whether binary tree is form of min heap
*/
//Structure of Binary Tree node
//Structure of Binary Tree node
class Node(var data: Int,var left: Node,var right: Node) {
	//make a tree node
	def this(data: Int) {
		//assign field values
		this(data, null,null);
	}
} 
class MyHeap(var root: Node) {
	
	def this() {
		this(null);
	}
	//Check that given binary tree is form of min heap or not
	def is_min_heap(root: Node): Boolean = {
		if (root != null) {
			if (root.left != null && root.left.data < root.data || root.right != null && root.right.data < root.data) {
				return false;
			}
			if (this.is_min_heap(root.left) == true && this.is_min_heap(root.right) == true) {
				return true;
			}
			return false;
		}
		return true;
	}
	//Display tree elements in order form
	def inorder(node: Node): Unit = {
		if (node != null) {
			this.inorder(node.left);

			//Print node value
			print(" " + node.data);
			this.inorder(node.right);
		}
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		val obj: MyHeap = new MyHeap();

		/* 
		    Make A Binary Tree
		    -----------------------
		               1
		             /   \
		            5     6
		           / \    / \
		          9   7  8   10
		         /   /  \     
		        13  12   11    
		                
		              
		    */
		//Insertion of binary tree nodes
		obj.root = new Node(1);
		obj.root.left = new Node(5);
		obj.root.right = new Node(6);
		obj.root.right.right = new Node(10);
		obj.root.right.left = new Node(8);
		obj.root.left.left = new Node(9);
		obj.root.left.left.left = new Node(13);
		obj.root.left.right = new Node(7);
		obj.root.left.right.right = new Node(11);
		obj.root.left.right.left = new Node(12);
		obj.inorder(obj.root);

		if (obj.is_min_heap(obj.root) == true) {
			print("\n Min heap Binary Tree \n");
		} else {
			print("\n Not a Min Heap Binary Tree \n");
		}
		/* 
		    Make A Binary Tree
		    -----------------------
		               1
		             /   \
		            5     6
		           / \    / \
		          9   7  8   10
		         /   /  \     \
		        13  12   11    2    
		    */
		obj.root.right.right.right = new Node(2);
		obj.inorder(obj.root);

		if (obj.is_min_heap(obj.root) == true) {
			print("\n Min heap Binary Tree \n");
		} else {
			print("\n Not a Min Heap Binary Tree \n");
		}
	}
}

Output

 13 9 5 12 7 11 1 8 6 10
 Min heap Binary Tree
 13 9 5 12 7 11 1 8 6 10 2
 Not a Min Heap Binary Tree
/*
  Swift Program
  Check whether binary tree is form of min heap
*/
//Structure of Binary Tree node
class Node {
	var data: Int;
	var left: Node?;
	var right: Node?;
	//make a tree node

	init(_ data: Int) {
		//assign field values
		self.data = data;
		self.left = nil;
		self.right = nil;
	}
}
class MyHeap {
	var root: Node?;
	init() {
		self.root = nil;
	}
	//Check that given binary tree is form of min heap or not
	func is_min_heap(_ root: Node?) -> Bool {
		if (root != nil) {
			if (root!.left != nil && root!.left!.data < root!.data || root!.right != nil && root!.right!.data < root!.data) {
				return false;
			}
			if (self.is_min_heap(root!.left) == true && self.is_min_heap(root!.right) == true) {
				return true;
			}
			return false;
		}
		return true;
	}
	//Display tree elements in order form
	func inorder(_ node: Node?) {
		if (node != nil) {
			self.inorder(node!.left);
			print(" ", node!.data, terminator: "");
			self.inorder(node!.right);
		}
	}
}
func main() {
	let obj: MyHeap = MyHeap();
	/* 
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     
	        13  12   11    
	                
	              
	    */
	//Insertion of binary tree nodes
	obj.root = Node(1);
	obj.root!.left = Node(5);
	obj.root!.right = Node(6);
	obj.root!.right!.right = Node(10);
	obj.root!.right!.left = Node(8);
	obj.root!.left!.left = Node(9);
	obj.root!.left!.left!.left = Node(13);
	obj.root!.left!.right = Node(7);
	obj.root!.left!.right!.right = Node(11);
	obj.root!.left!.right!.left = Node(12);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		print("\n Min heap Binary Tree \n", terminator: "");
	} else {
		print("\n Not a Min Heap Binary Tree \n", terminator: "");
	}
	/* 
	    Make A Binary Tree
	    -----------------------
	               1
	             /   \
	            5     6
	           / \    / \
	          9   7  8   10
	         /   /  \     \
	        13  12   11    2    
	    */
	obj.root!.right!.right!.right = Node(2);
	obj.inorder(obj.root);
	if (obj.is_min_heap(obj.root) == true) {
		print("\n Min heap Binary Tree \n", terminator: "");
	} else {
		print("\n Not a Min Heap Binary Tree \n", terminator: "");
	}
}
main();

Output

  13  9  5  12  7  11  1  8  6  10
 Min heap Binary Tree
  13  9  5  12  7  11  1  8  6  10  2
 Not a Min Heap Binary Tree

Time Complexity

The time complexity of the is_min_heap function is O(n), where n is the number of nodes in the binary tree. This is because each node is visited exactly once during the traversal.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment