Given the
rootof a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).Constraints:
- The number of nodes in the tree is in the range
[0, 2000].-1000 <= Node.val <= 1000
While this is technically a tree problem, it is actually a graph problem in disguise! Think about what level order traversal is asking us to do:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
queue = [root]
while queue:
...
for node in queue:
...
# add children to queue
There are a few tricky things we have to consider before we get the full solution.
root is empty we should immediately return an empty list; similarly, we should avoid adding empty children.def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
from collections import deque
if root is None:
return []
ans = []
queue = deque([root])
while queue:
level = []
# only process nodes of this level
# when len(queue) is evaluated, the queue only contains all nodes
# of some level, and no other levels.
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
# only process non-empty nodes
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
ans.append(level)
return ans
Notice that since this is a tree, the BFS runtime simplifies to . This is not changed further since the processing time at each node remains constant time, and all other operations are also constant time.
Since we are dealing with binary trees, each node has at most 2 children. That means that in the worst case, each level has nodes where is the current depth. Therefore, our space complexity is .
However, this can be simplified. The worst case occurs at the lowest level of our binary tree, where there are nodes where is the height. But think about the number of nodes above it:
This means that , so . This means that our space complexity is in fact !