Problem
Given theroot of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Examples
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -1000 <= Node.val <= 1000
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 102 with 13 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 102 # by problem number
lcpy gen -s binary_tree_level_order_traversal # by problem name
root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
from collections import deque
from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(w) where w is max width of tree
def level_order(self, root: TreeNode[int] | None) -> list[list[int]]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
| Time | Space |
|---|---|
| O(n) | O(w) where w is max width of tree |