958. Check Completeness of a Binary Tree
Problem
Decide whether a binary tree is complete: every level is full except possibly the last, whose nodes are all as far left as possible.
Example: [1,2,3,4,5,6] → true; [1,2,3,4,5,null,7] → false
BFS including null children. In a complete tree, once you see a null, every later node in BFS order must also be null.
Complexity: O(n).
class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
q, seen_null = deque([root]), False
while q:
node = q.popleft()
if not node:
seen_null = True
continue
if seen_null:
return False
q.append(node.left)
q.append(node.right)
return True
assert Solution().isCompleteTree(make_tree([1, 2, 3, 4, 5, 6])) is True
assert Solution().isCompleteTree(make_tree([1, 2, 3, 4, 5, None, 7])) is False
class Solution {
public boolean isCompleteTree(TreeNode root) {
Deque<TreeNode> q = new LinkedList<>(); // LinkedList allows null elements
q.add(root);
boolean seenNull = false;
while (!q.isEmpty()) {
TreeNode n = q.poll();
if (n == null) { seenNull = true; continue; }
if (seenNull) return false;
q.add(n.left);
q.add(n.right);
}
return true;
}
}
func isCompleteTree(root *TreeNode) bool {
q, seenNil := []*TreeNode{root}, false
for len(q) > 0 { // BFS including nils: no node may come after a nil
node := q[0]
q = q[1:]
if node == nil {
seenNil = true
continue
}
if seenNil {
return false
}
q = append(q, node.Left, node.Right)
}
return true
}