-
Notifications
You must be signed in to change notification settings - Fork 17
/
BTIsHeapOrNot.java
43 lines (31 loc) · 984 Bytes
/
BTIsHeapOrNot.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
class Solution
{
boolean isHeap(Node node){
return valueCheck(node, Integer.MAX_VALUE) && levelCheck(node);
}
boolean valueCheck(Node node, int value) {
if(node==null) return true;
boolean ans = false;
if(node.data < value) ans = true;
return ans && valueCheck(node.left, node.data) && valueCheck(node.right, node.data);
}
boolean levelCheck(Node node) {
Queue<Node> q = new LinkedList<>();
q.add(node);
int level=0;
boolean check = false;
while(!q.isEmpty()) {
int size = q.size();
if(size != Math.pow(2, level++)) check = true;
for(int i=1; i<=size; i++) {
Node temp = q.remove();
if(temp.left != null) q.add(temp.left);
if(temp.right != null) q.add(temp.right);
}
if(check && !q.isEmpty()) {
return false;
}
}
return true;
}
}