Binary Tree

Level Order Visualizer

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.

QueueThe front of the queue is the next node to write. Children are added at the back, so the next level starts only after this level is empty.
One list per levelThe driver prints each list on its own line. Missing children are skipped, so -1 never appears in the output.

A single queue is enough. The length of the queue at the start of a round is the width of that level.

Interactive solution

One highlighted level at a time
queue = [root]
while queue:
this level = everything now in the queue
write those values
push each left and right child
the next round is the next level
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each node enters and leaves the queue once.
Extra memoryO(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