Level order with a queue

Video lessonComing soon

1 News spreads one level at a time

The CEO from the tree basics lesson has news. At minute 0, only she knows it. At minute 1, she tells her two reports. At minute 2, they tell theirs. Each person hears it one minute after their boss, like a ripple spreading out from a stone.

1425869
Minute 2: 1, 5 and 9 hear the news
MinuteWho hears the news
08
14, 6
21, 5, 9
32

The people who hear it in the same minute form one level. A level order traversal visits the tree in this order: level by level, and left to right inside a level. Most problems want each level as its own list: [[8], [4, 6], [1, 5, 9], [2]].

The walks so far cannot give this. Preorder visits 8, 4, 1, 5, 2, 6, 9. It finishes all of 4's team before it reaches 6, because it goes deep first. Level order goes wide first, so it is also called breadth-first search (BFS).

2 A queue keeps the levels in order

Each person who hears the news joins a line to pass it on. The person at the front tells their reports, and the reports join the back of the line.

That line is a queue: first in, first out. Level 2 joins only when 4 or 6 is served, so 4 and 6 are already ahead of them. The line hands out a whole level before the next one starts:

pending = a queue holding the root
while pending is not empty:
    node = take from the front of pending
    write node.val
    add node.left to the back, if it is not null
    add node.right to the back, if it is not null

On our tree, it writes 8 4 6 1 5 9 2: the levels, in order. The tree basics lesson read the input array with this same queue.

A stack would not work. It hands back the newest node, so the walk dives deep, as in the iterative traversals lesson. The same loop with a stack writes 8 6 9 4 5 2 1. Here is each one after two nodes are taken:

615
Queue after 8 and 4: 6 comes next
49top →
Stack after 8 and 6: 9 comes before 4

The flat list has one problem. It has lost where each level ends.

3 Where a level ends: count first

Most of the time, the queue mixes two levels. After 4 is taken, it holds 6 from level 1, then 1 and 5 from level 2. But at one moment it holds exactly one level: just before the level's first node is taken. Then its size is the number of nodes in the level.

So each round of the loop starts by reading levelSize, the queue's size. Then it takes exactly levelSize nodes. Those are the whole level. The children added meanwhile wait at the back for the next round.

This holds every round. At the start, the queue holds only the root, which is level 0. A round takes all of one level and adds all their children in order, which is the whole next level.

In the queue below, blue marks the level being read, orange the next level, and a crossed box the node just taken:

Reading levels with a queue
1425869
8
Start: the queue holds the root
level 0level 1level 2level 3
levels

The same run as a table, one row per round:

RoundQueue at startlevelSizeTakenAddedLevel written
18184, 6[8]
24, 624, 61, 5, 9[4, 6]
31, 5, 931, 5, 92[1, 5, 9]
4212nothing[2]

Each round's "Added" is the next round's "Queue at start". The queue starts every round holding one whole level, and nothing else.

4 levelOrder in code, and its cost

The inner loop runs levelSize times, a number fixed before it starts:

C++

front, then pop. pop() removes the front but returns nothing, so we read the node with front() first.

ArrayDeque as the queue. offer adds at the back and poll takes from the front, both in O(1). It refuses null and throws, so the checks before each offer are needed.

deque, not a list. popleft() takes from the front in O(1). A list's pop(0) shifts every value left, so it is O(n).

An array with a front index. JavaScript has no queue type, and shift() moves every value. Reading pending[front] and adding 1 to front is O(1). The taken nodes stay in the array, so this version keeps O(n) memory.

A slice as the queue. pending[1:] drops the front without copying anything, so each take is O(1).

VecDeque as the queue. push_back and pop_front are both O(1). pop_front returns an Option, and let … else leaves the loop if it is ever None. clone() on a child copies the Rc, not the subtree.

Queue<T>. Enqueue adds at the back and Dequeue takes from the front, both in O(1). Dequeue on an empty queue throws, but the loop takes only levelSize nodes, so it never does.

Cost. Every node joins the queue once and leaves once, so the time is O(n). The queue holds about one level at a time, so the extra space is O(w), where w is the number of nodes on the widest level.

Tree of about 10⁵ nodesBFS queueDFS call stack
Perfectabout 5 × 10⁴about 17
Skewed1about 10⁵

A perfect tree keeps about half its nodes on its last level, so a wide tree costs BFS the most and DFS the least. A skewed tree is the other way round.

5 One loop, many problems

Most problems in this subtopic are the loop above with one line changed. The round tells us the level, and i tells us where in the level we are.

1425869
Seen from the right: 8, 6, 9 and 2
  • Right side view. Keep the node where i == levelSize - 1, the last of each round. Our tree gives 8, 6, 9, 2. The 2 hangs off the left side, so following right children down would miss it.
  • Zigzag. Reverse every second level's list: [[8], [6, 4], [1, 5, 9], [2]]. The queue's order stays the same; only the written list flips.
  • Bottom up. Reverse levels once at the end: [[2], [1, 5, 9], [4, 6], [8]].
  • Averages. Add up the round and divide by levelSize: 8, 5, 5, 2. Keep the sum in a 64-bit type, since two large values can already pass what a 32-bit int holds.
  • Next pointers. Inside a round, point each node's next at the node taken after it. The round's last node points to null.
  • Minimum depth. Return the round number when the first leaf comes out: round 3 on our tree, for the leaf 1. BFS stops there. A DFS must try every path to be sure none is shorter.

A DFS can group by level too, if it passes the depth down:

collect(node, depth):
    if node is null: return
    if depth == size of levels: add an empty list to levels
    add node.val to levels[depth]
    collect(node.left, depth + 1)
    collect(node.right, depth + 1)

Left goes before right, so each list still fills left to right. It takes O(h) space instead of O(w), and it is simpler when the code is already recursive.

6 A number carried with each node

Some questions need more than the level. Then each queue entry holds the node and one number about it.

Maximum width measures a level from its leftmost node to its rightmost, gaps included. We number the nodes as the tree basics lesson numbered a complete tree: the root is 0, and position p has its children at 2p + 1 and 2p + 2.

1425869
Level 2 holds three nodes
3194026
Their positions run from 3 to 6

A level's width is its last position − its first + 1. Level 2 has width 6 − 3 + 1 = 4, counting the gap at 5. No level is wider, so the answer is 4.

Positions double at each level. Down a chain of left children they go 0, 1, 3, 7, 15, and about 64 levels down they pass what 64 bits hold. So at the start of each round, we subtract the level's first position from every position in it. Both ends move by the same amount, so the width stays the same and the numbers stay small.

C++

Use long long positions. After the subtraction, a child's position can still reach twice the widest level, which can pass what an int holds.

Use long positions. After the subtraction, a child's position can still reach twice the widest level, which can pass what an int holds.

No overflow, but subtract anyway. Integers grow as needed, so nothing breaks. Without the subtraction, a deep tree's positions grow to dozens of digits, and every step gets slower.

Exact only up to about 9 × 10¹⁵. Without the subtraction, a chain of about 53 levels passes that, and positions go wrong with no error. With it, they stay small.

int is 64 bits on today's machines, so it holds the positions once we subtract.

Use i64 positions. An i32 can overflow, and in a debug build that stops the program.

Use long positions. After the subtraction, a child's position can still reach twice the widest level, which can pass what an int holds.

The views from above and below carry a column instead: 0 for the root, one less for a left child, one more for a right child.

−2−1−10012
Each node's column

BFS meets higher levels first, so the top view keeps the first node it meets in each column: 1, 4, 8, 6, 9. The bottom view keeps the last: 1, 2, 5, 6, 9. Vertical order groups all the nodes by column.

7 Spreading from any node

The ripple does not have to start at the root. In some problems, it starts at a node such as 5 and spreads one edge a minute in every direction, down to the children and up to the parent.

A TreeNode has no pointer up. So we first walk the tree once and store each node's parent in a map. Then the BFS starts at 5, and a node's neighbours are its left child, its right child and its parent. A visited set stops the news from flowing back the way it came. Each round is one minute.

1425869
The news starts at 5
2110234
The minute each node hears it

The nodes at distance 2 from 5 are 8 and 1. The last node to hear it is 9, at minute 4. The graphs lesson on BFS uses this same loop on graphs, where a node can have any number of neighbours.

8 Mistakes, and when to use it

  • Reading the size inside the loop. A loop written as while i < size of pending reads the size again after every take and add. On our tree, it writes [[8, 4, 6], [1, 5], [9], [2]]. Read the size once, before the inner loop.
  • Adding null children. The null reaches the front later, and reading its value is a Runtime Error.
  • Taking from the front of an array. v.erase(v.begin()) shifts every value left, so each take is O(n). With 10⁵ nodes, that is around 10¹⁰ steps, and it gets TLE.
  • The empty tree. [] gives a null root. Putting it in the queue makes the first take read a null. Return an empty list first.

The subtopic's sign is a question about levels, a view from one side, or a distance from a node:

  • Levels. A list, sum, average, largest value or width for each level.
  • A view from one side. The first or last node of each round, or the first or last node in each column.
  • A distance from a node. BFS from that node, with parent links, one round per step.
  • The nearest of something. The shallowest leaf, or the first node that matches. BFS can stop at the first one it finds.

The next lesson asks which traversals, given together, pin down exactly one tree.

Before writing a BFS, decide what one round means: a level, a minute, a step away. Read the queue's size first, then take exactly that many.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.