-
Notifications
You must be signed in to change notification settings - Fork 22
/
BinaryTreeIsHeap.java
62 lines (53 loc) · 1.96 KB
/
BinaryTreeIsHeap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.company.amazon;
import com.company.amazon.BinaryTree.Node;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTreeIsHeap {
public static void main(String[] args) {
Node root = new Node(100);
root.left = new Node(25);
root.right = new Node(20);
root.left.left = new Node(17);
if (binaryTreeIsMaxHeap(root)) {
System.out.println("Yes it's a Max heap");
}
}
public static boolean binaryTreeIsMaxHeap(Node root) {
Queue<Node> queue = new LinkedList<>();
Boolean isNullInserted = false;
queue.add(root);
while (!queue.isEmpty()) {
Node dequeued = queue.poll();
if (isNullInserted && dequeued != null) {
System.out.println("Binary Tree doesn't satisfy Complete Tree property");
return false;
} else if (!isNullInserted) {
if (dequeued == null) {
isNullInserted = true;
continue;
}
if (dequeued.left != null) {
if (dequeued.left.data > dequeued.data) {
System.out.println("MAX heap left child should be small property doesn't satisfy");
return false;
} else {
queue.add(dequeued.left);
}
} else {
queue.add(dequeued.left);
}
if (dequeued.right != null) {
if (dequeued.right.data > dequeued.data) {
System.out.println("MAX heap right child should be small property doesn't satisfy");
return false;
} else {
queue.add(dequeued.right);
}
} else {
queue.add(dequeued.right);
}
}
}
return true;
}
}