Problem: Return the level-order traversal of a binary tree's node values from left to right and level by level
Input: The root node of a binary tree
Output: A list of lists containing the values of the the binary tree by level
Example:
1
/ \
2 3
/ \
4 5
-> [[1],[2,3],[4,5]]
We can traverse the binary tree level by level using Breadth-First Search (BFS) with a queue. The key idea is to use the queue to maintain the correct order of nodes and to use the number of elements in the queue to separate each level.
from collections import deque
class Solution:
def levelOrder(self, root):
# Initialize
res = []
if not root: # early guard
return res
queue = deque([root]) # implement the seed
# Run BFS
while queue:
n = len(queue)
temp = []
# for loop for each level
for _ in range(n):
# base
node = queue.popleft()
temp.append(node.val)
# propagate
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
# Return the result
return res
working
Time complexity: O(n), where n is the number of nodes in the binary tree, since each node is visited exactly once.
Space compleixty: O(n), because in the worst case, the queue can store up to n/2 nodes and the result list can store up to n nodes