MediumNo. 0958
Check Completeness of a Binary Tree — LeetCode 958 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Breadth-First Search, Binary Tree
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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
- Time
- O(V+E)
- Space · auxiliary
- O(V)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0102 | Binary Tree Level Order Traversal | Medium |
| 0103 | Binary Tree Zigzag Level Order Traversal | Medium |
| 0107 | Binary Tree Level Order Traversal II | Medium |
| 0919 | Complete Binary Tree Inserter | Medium |
| 1609 | Even Odd Tree | Medium |
| 2471 | Minimum Number of Operations to Sort a Binary Tree by Level | Medium |
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.