Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Input:
3
/ \
9 20
/ \
15 7
Output: [[3], [9, 20], [15, 7]]
Input:
1
/ \
2 3
/ \
4 5
Output: [[1], [2, 3], [4, 5]]
[0, 2000]
.-1000 <= Node.val <= 1000
None
, and the function should return an empty list []
.To achieve a level order traversal, we can use a queue data structure to perform a breadth-first search (BFS). The BFS approach will help in processing nodes level by level from left to right. Here’s a step-by-step breakdown:
None
, return an empty list []
.result
to store the level order traversal.level_size
).current_level
to store the values of nodes at the current level.current_level
.current_level
to result
.result
containing the level order traversal.from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def levelOrder(root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(current_level)
return result
N
is the number of nodes in the tree. Every node is processed exactly once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?