Maximum Width of Binary Tree — LeetCode 662 Python Solution
MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
- Problem
- #662
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.
Example
- Input
- root = [1,3,2,5,3,null,9]
- Output
- 4
- Explanation
- The maximum width exists in the third level with length 4 (5,3,null,9).
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 widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
ans = 0
q = deque([(root, 1)])
while q:
ans = max(ans, q[-1][1] - q[0][1] + 1)
for _ in range(len(q)):
root, i = q.popleft()
if root.left:
q.append((root.left, i << 1))
if root.right:
q.append((root.right, i << 1 | 1))
return ansComplexity
| 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 662. Maximum Width of 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 662. Maximum Width of Binary Tree?
- LeetCode 662. Maximum Width of Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 662. Maximum Width of Binary Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 662. Maximum Width of Binary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 662. Maximum Width of Binary Tree cover?
- LeetCode 662. Maximum Width of Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.