SDE & MLE Prep

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