What is Level Order
Level order reads the tree one row at a time, left to right, starting at the root. A queue holds the nodes that belong to the current row.
1 2 3 4 5 1 2 3 4 5
Approach
Put the root in a queue. Each round takes every node that is already waiting, writes those values as one level, and pushes their children for the next round.
A single queue is enough. The length of the queue at the start of a round is the width of that level.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node enters and leaves the queue once. |
| Extra memory | O(w) | The queue holds one level, and w is the widest level. |
Implementation
def solve(self, root):
if not root: return []
q, out = [root], []
while q:
nxt, row = [], []
for node in q:
row.append(node.val)
if node.left: nxt.append(node.left)
if node.right: nxt.append(node.right)
out.append(row)
q = nxt
return out