NeetCode #439LC-662MediumTrees
← Back to All Problems#439 · #662 · Maximum Width of Binary Tree(二叉树最大宽度)
📌 Problem Statement & Constraints
Given the root of a binary tree, return the maximum width of the tree: the maximum number of nodes between the leftmost and rightmost non-null nodes of any level, counting the nulls in between as if the tree were a complete tree. Constraints: the number of nodes is in
[1, 3000], -100 <= Node.val <= 100.💡 Core Algorithmic Approaches
- Assign each node a position index as in a heap: the left child is
2iand the right child2i + 1, with the root at 0. - The width of a level is
last_index - first_index + 1, where the indices include the implicit nulls. - A level-order traversal with a frozen level size gives the first and last indices directly.
- Important: the indices grow exponentially with depth, so subtract each level's first index (or use Python's unbounded integers, which handle it but waste memory).
💻 Benchmark Python3 Implementation
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
from collections import deque
q = deque([(root, 0)]) # (node, heap-style index)
best = 0
while q:
n = len(q)
first = q[0][1]
last = q[-1][1]
best = max(best, last - first + 1)
base = first # normalise to keep indices small
for _ in range(n):
node, i = q.popleft()
i -= base
if node.left:
q.append((node.left, 2 * i))
if node.right:
q.append((node.right, 2 * i + 1))
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is enqueued and dequeued once.
💾 Space Complexity
O(w) for the widest level.
⚠️ Interview Pitfalls & Follow-ups
- Counting only the actual nodes: the width includes the null gaps, which is why heap-style indices are used.
- Skipping the index normalisation: for a skewed tree the indices double every level, so a depth-3000 tree would need astronomically large integers.
- Using a DFS without tracking positions: the width is a per-level property.
- Assuming the tree is complete: the width is measured on the virtual complete tree, not the actual one.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
二叉树最大宽度
给你一棵二叉树的根节点 root,返回树的 最大宽度 。树的最大宽度是所有层中最大的宽度。每一层的宽度被定义为该层最左和最右的非空节点(即,两个端点)之间的长度。将这个二叉树视作与满二叉树结构相同,两端点间会出现一些延伸到这一层的 null 节点,这些 null 节点也计入长度。题目数据保证答案将会在 32 位带符号整数范围内。约束:树中节点的数目范围是 [1, 3000];-100 ≤ Node.val ≤ 100。
核心要点
- BFS + 完全二叉树编号(标准解) :给每个节点编号——根为 0,左孩子为 2 × pos ,右孩子为 2 × pos + 1 。每层的宽度 = 该层最右编号 − 最左编号 + 1。
- 为什么编号能反映宽度 :满二叉树中,编号差恰好等于「两端点之间按层排列的位置数」,因此包含了中间的空位。
- 注意编号溢出 :链状树时编号可达 2^3000,Python 的大整数能处理,但 C++/Java 需要取模或改用「相对偏移」技巧(每层减去最小编号)。
- 复杂度 :O(n) 时间、O(w) 空间。
常见陷阱
- 只统计非空节点个数 :题目要求把中间的空位也算进宽度,必须用编号差。
- 编号溢出 :C++/Java 中长链树的编号会溢出。可用「每层减去最小编号」的相对偏移技巧避免。
- 忘记记录最右编号 :必须在处理本层最后一个节点时记录 last 。
- 用 DFS 记录每层的行列号再计算 :也可行,但 BFS 更直接。
参考实现
from collections import deque
class Solution:
def widthOfBinaryTree(self, root: 'TreeNode') -> int:
best = 0
q = deque([(root, 0)]) # (节点, 完全二叉树编号)
while q:
size = len(q)
first = last = 0
for i in range(size):
node, pos = q.popleft()
if i == 0:
first = pos # 本层最左编号
if i == size - 1:
last = pos # 本层最右编号
if node.left:
q.append((node.left, 2 * pos))
if node.right:
q.append((node.right, 2 * pos + 1))
if last - first + 1 > best:
best = last - first + 1
return best