Home Leetcode

102. Binary Tree Level Order Traversal

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).

Constraints:

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.

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

Time Complexity

Notice that since this is a tree, the BFS runtime simplifies to O(V)=O(n)\mathcal{O}(V) = \mathcal{O}(n). This is not changed further since the processing time at each node remains constant time, and all other operations are also constant time.

Space Complexity

Since we are dealing with binary trees, each node has at most 2 children. That means that in the worst case, each level has 2d2^d nodes where dd is the current depth. Therefore, our space complexity is O(2d)\mathcal{O}(2^d).

However, this can be simplified. The worst case occurs at the lowest level of our binary tree, where there are 2h2^h nodes where hh is the height. But think about the number of nodes above it:

1+2++2h1=2h11 + 2 + \dotsb + 2^{h-1} = 2^h - 1

This means that n=2(2h)+1n = 2 (2^h) + 1, so 2h=n212^h = \frac{n}{2} - 1. This means that our space complexity is in fact O(n)\mathcal{O}(n)!