102. Binary Tree Level Order Traversal
Description
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).
Explaination
A classic BFS question: using a single queue / 2 lists / dummy node to solve the problem.
Code
single queue
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res = []
'''
1-step: add level 1 nodes
Using collections.deque in python.
This gives a 2-sided queue
'''
queue = collections.deque([root])
'''
2-step: while queue is not empty
Now we have all the nodes on the same level in this queue
'''
while queue:
'''
append all the values of the same-level nodes to the result list
'''
res.append([node.val for node in queue])
'''
3-step: add next level nodes
For all the node in current queue, add their children.
In for loop, we use range to control the for-loop rounds.
It is fixed as we are using range(len(queue)) which generates a iterator [0, len(queue)].
The number of loops will not be changed even if queue is changed.
'''
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
2 lists
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res = []
'''
we don't need to pop any elements, so list is enough
The nodes in one level in recorded in a single list
Their children are recorded in another list
After checking all the nodes in current level, we take next_level as current_level and continue our traversal.
'''
current_level = [root]
while current_level:
res.append([node.val for node in current_level])
next_level = []
for node in current_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current_level = next_level
return res
dummy node
Less indent
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res, level = [], []
'''
Add None as dummy node at the end of each level
as long as they have children.
'''
queue = collections.deque([root, None])
while queue:
node = queue.popleft()
if node is None:
res.append(level)
level = []
'''
If there is no following nodes, then this is the end of queue.
Only add dummy node when there are following nodes in queue
'''
if queue:
queue.append(None)
continue
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res