Skip to content

Instantly share code, notes, and snippets.

@anil477
Created July 15, 2017 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/070a824d4d4935f99c73c38de3c9ea3d to your computer and use it in GitHub Desktop.
Save anil477/070a824d4d4935f99c73c38de3c9ea3d to your computer and use it in GitHub Desktop.
Check if a given Binary Tree is Heap
// http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-heap/
// Using level order traversal
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
class BinaryTree {
Node root;
boolean checkMaxHeap()
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
boolean leftNullFound = false;
while(!queue.isEmpty()) {
Node temp = queue.poll();
if (temp.left != null)
{
// if a null left node has been found, then no other left node should exist to satify the complete binary tree property
if(leftNullFound == true)
{
return false;
}
if (temp.data > temp.left.data)
{
queue.add(temp.left);
}
else
{
return false;
}
}
else
{
leftNullFound = true;
}
if(temp.right != null)
{
// if a null left node has been found, then no right node should exist to satify the complete binary tree property
if(leftNullFound == true)
{
return false;
}
if (temp.data > temp.right.data)
{
queue.add(temp.right);
} else{
return false;
}
}
}
return true;
}
public static void main(String args[])
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(97);
tree_level.root.left = new Node(46);
tree_level.root.right = new Node(37);
tree_level.root.left.left = new Node(12);
tree_level.root.left.right = new Node(3);
//tree_level.root.left.right.left = new Node(2);
//tree_level.root.left.right.right = new Node(1);
tree_level.root.right.left = new Node(7);
tree_level.root.right.right = new Node(31);
boolean res = tree_level.checkMaxHeap();
if (res) {
System.out.println(" Max Heap");
} else {
System.out.println(" Not a Max Heap");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment