Check Completeness of a Binary Tree — LeetCode 958 Python Solution
- Problem
- #958
- Pattern
- Tree Traversal
- 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
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(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.