-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCompleteness_Binary_Tree.java
More file actions
60 lines (50 loc) · 1.54 KB
/
Completeness_Binary_Tree.java
File metadata and controls
60 lines (50 loc) · 1.54 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
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class CheckCompletenessBinaryTree {
public static boolean isComplete(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
// A null node should not be followed by any non-null nodes.
while (!queue.isEmpty() && queue.peek() == null) {
queue.poll();
}
// If there are any non-null nodes left, the tree is not complete.
if (!queue.isEmpty()) {
return false;
}
} else {
queue.add(node.left);
queue.add(node.right);
}
}
return true;
}
public static void main(String[] args) {
// Example usage
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
if (isComplete(root)) {
System.out.println("The binary tree is complete.");
} else {
System.out.println("The binary tree is not complete.");
}
}
}