Your solution works, but it isn’t very “pythonic.” In particular:
- Manually managing an index +
None‐sentinel makes the code harder to read.
- A simple
collections.deque + looping over the current queue length gives you level boundaries for free.
- You can use more expressive names (
queue/level vs. q/cur_level) and list‐comprehensions to keep it concise.
Here’s a more idiomatic BFS‐by‐level in Python:
from collections import deque
from typing import Optional, List
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
level_vals = []
# Process exactly one level’s worth of nodes
for _ in range(level_size):
node = queue.popleft()
level_vals.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_vals)
return result
Why this is more “pythonic”:
deque.popleft() is O(1); appending/popping from a Python list’s front is O(n).
- You don’t need an explicit
None marker—just record the queue’s length at each level.
- Clear variable names (
queue, level_vals) and structured loops improve readability.
Even more concise (using a list‐comprehension for the next level):
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
result, level = [], [root]
while level:
result.append([node.val for node in level])
# build next level
level = [child
for node in level
for child in (node.left, node.right)
if child]
return result
Both approaches are widely used in the Python community. Pick the one you find clearest!