-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0958-check-completeness-of-a-binary-tree.java
More file actions
60 lines (58 loc) · 1.75 KB
/
0958-check-completeness-of-a-binary-tree.java
File metadata and controls
60 lines (58 loc) · 1.75 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isCompleteTree(TreeNode root) {
int depth = depth(root);
if (depth == 1)
return true;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int lvl = 1;
boolean end = false;
while (!q.isEmpty()) {
int size = q.size();
int countNodes = 0;
for (int i=0; i<size; i++) {
TreeNode curr = q.poll();
countNodes++;
if (lvl == depth - 1) {
if (end && (curr.left != null || curr.right != null)) {
return false;
}
if (curr.left == null && curr.right != null) {
return false;
}
if (curr.left == null || curr.right == null) {
end = true;
}
}
else {
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
}
}
if (lvl != depth && countNodes != Math.pow(2, lvl-1))
return false;
lvl++;
}
return true;
}
public int depth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
}