LeetCode 958. Check Completeness of a Binary Tree

Post by ailswan Aug. 18, 2024

958. Check Completeness of a Binary Tree

Problem Statement

link: LeetCode.cn LeetCode Given the root of a binary tree, determine if it is a complete binary tree.

In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

Input: root = [1,2,3,4,5,6] Output: true

Input: root = [1,2,3,4,5,null,7] Output: false

Constraints: The number of nodes in the tree is in the range [1, 100]. 1 <= Node.val <= 1000

Solution Approach

The solution uses a BFS approach to traverse the tree level by level, ensuring that no non-None nodes appear after a None, which would violate the completeness property of the binary tree.

Algorithm

  1. Level Order Traversal: Perform a BFS traversal using a queue to visit each node level by level, ensuring that nodes are processed in the correct order.
  2. Check for None Nodes: Track when a None node is encountered, indicating a potential gap in the tree, which should be followed only by other None nodes.
  3. Validation: If any non-None node is found after a None, return False to indicate the tree is not complete; otherwise, if no violations are found, return True.

Implement

    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
        empty = False
        q = deque([root])
        while q:
            cur = q.popleft()
            if not cur:
                empty =  True
            else:
                if empty: # if there are some more node behind None,it is not valid
                    return False
                q.append(cur.left) 
                q.append(cur.right)       
        return True