Check Completeness of a Binary Tree — LeetCode 958 Python Solution

MediumTreeBreadth-First SearchBinary Tree
Problem
#958
Reading time
3 min

The problem

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.

Example

Input
root = [1,2,3,4,5,6]
Output
true
Explanation
Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Python solution

Python
# Definition for a binary tree node.
# 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: TreeNode) -> bool:
        q = deque([root])
        while q:
            node = q.popleft()
            if node is None:
                break
            q.append(node.left)
            q.append(node.right)
        return all(node is None for node in q)

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 958. Check Completeness of a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 958. Check Completeness of a Binary Tree?
LeetCode 958. Check Completeness of a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 958. Check Completeness of a Binary Tree?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 958. Check Completeness of a Binary Tree?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 958. Check Completeness of a Binary Tree cover?
LeetCode 958. Check Completeness of a Binary Tree is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview