CodeArchon

mediumTreesAmazonBloombergGoogleFacebook

Wave Broadcast Scanner

A wireless antenna broadcasts a spatial ping. The network analyzer logs the propagation waves horizontal level-by-level.

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

Choose approach

3
wave
9
20
15
7
1/12
Narrationstep 1 of 12

Init level traversal depth 0. Count 1 active broadcast sources.

1def levelOrder(root: Optional[TreeNode]) -> List[List[int]]:
2 if not root:
3 return []
4 result = []
5 queue = collections.deque([root])
6 while queue:
7 level_size = len(queue)
8 current_level = []
9 for _ in range(level_size):
10 node = queue.popleft()
11 current_level.append(node.val)
12 if node.left: queue.append(node.left)
13 if node.right: queue.append(node.right)
14 result.append(current_level)
15 return result
Variables
depth=0
queue=3
currentLevel=[]
result=[]

How to think about it

  1. Place root inside a FIFO Queue.
  2. At every level loop, poll size elements from the queue.
  3. Pull node values, and queue their valid left / right descendants.
  4. Push completed levels array into global tracker.

Edge cases to catch in interview

  • Empty target tree -> returns vacant array.
  • Highly unbalanced nodes straight down -> returns list of single assemblies.

Examples

Example 1[[3], [9,20], [15,7]]
{"arr":[3,9,20,null,null,15,7]}
Example 2[[1]]
{"arr":[1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed