Tree Traversal & BST · 12 min · free lesson

Level-Order BFS: When to Use It

Recognise the problem shape before choosing Level-Order BFS.

Core idea

Newly enqueued children belong to the next level. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Queue nodes and process exactly the current queue length to preserve level boundaries.

O(n) time · O(w) queue62 execution steps
main · before line 40Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example input[1,2,3,4,5,null,6]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 40
type Tree = Option<Box<Node>>;
struct Node {
    value: i32,
    left: Tree,
    right: Tree,
}
fn node(value: i32, left: Tree, right: Tree) -> Tree {
    Some(Box::new(Node { value, left, right }))
}
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn level_sums(root: &Tree) -> Vec<i32> {
    let mut queue = std::collections::VecDeque::new();
    let mut out = Vec::new();
    if let Some(n) = root {
        queue.push_back(n.as_ref());
    }
    while !queue.is_empty() {
        let mut sum = 0;
        for _ in 0..queue.len() {
            let n = queue.pop_front().unwrap();
            sum += n.value;
            if let Some(left) = &n.left {
                queue.push_back(left);
            }
            if let Some(right) = &n.right {
                queue.push_back(right);
            }
        }
        out.push(sum);
    }
    out
}
 
fn main() {
    let result = csv(level_sums(&node(
        1,
        node(2, node(4, None, None), node(5, None, None)),
        node(3, None, node(6, None, None)),
    )));
    println!("{result}");
}

Try your own version

Compare the visible input `[1,2,3,4,5,null,6]` with `[2,1,3]`. Predict why their results are `1,5,15` and `2,4`. Then change one legal value and explain whether the same invariant, newly enqueued children belong to the next level, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Tree Traversal & BST infographic; panel 4 illustrates Tree Level Order.
Tree Level Order: follow panel 4 to see the operation, then trace the lesson's own example.

Understand it

The sample levels contain [1], [2,3], and [4,5,6]. Their sums are 1,5,15. Reading the initial queue length confines each inner loop to one level even as children are enqueued.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Parse the compact level-order binary tree, where null omits a node. Return the sum of each level from the root downward. The visible fixture is [1,2,3,4,5,null,6] and its example result is 1,5,15. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Level-Order BFS when it asks for shortest unweighted depth and level summaries. Here the concrete task is: Parse the compact level-order binary tree, where null omits a node. Return the sum of each level from the root downward. The visible input [1,2,3,4,5,null,6] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Look for hierarchy and parent-child structure; a plain sequence algorithm loses the branching relationships. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Queue nodes and process exactly the current queue length to preserve level boundaries. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A tree result is built from a node and its children. Decide whether information flows downward, upward, or in level order. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n) time · O(w) queue; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 1,5,15 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test a missing root, a leaf, a skewed tree, and equal or duplicate values when ordering rules depend on them. Use references for read-only traversals and make the stack or queue explicit when recursion depth might be large. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Queue nodes and process exactly the current queue length to preserve level boundaries.

When to use it: shortest unweighted depth and level summaries

Complexity: O(n) time · O(w) queue

Input: [1,2,3,4,5,null,6]

Read the code

type Tree = Option<Box<Node>>;
struct Node {
    value: i32,
    left: Tree,
    right: Tree,
}
fn node(value: i32, left: Tree, right: Tree) -> Tree {
    Some(Box::new(Node { value, left, right }))
}
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn level_sums(root: &Tree) -> Vec<i32> {
    let mut queue = std::collections::VecDeque::new();
    let mut out = Vec::new();
    if let Some(n) = root {
        queue.push_back(n.as_ref());
    }
    while !queue.is_empty() {
        let mut sum = 0;
        for _ in 0..queue.len() {
            let n = queue.pop_front().unwrap();
            sum += n.value;
            if let Some(left) = &n.left {
                queue.push_back(left);
            }
            if let Some(right) = &n.right {
                queue.push_back(right);
            }
        }
        out.push(sum);
    }
    out
}

fn main() {
    let result = csv(level_sums(&node(
        1,
        node(2, node(4, None, None), node(5, None, None)),
        node(3, None, node(6, None, None)),
    )));
    println!("{result}");
}

Complete std-only tree-level-order program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Level-Order BFS on input [1]. Which result follows from the documented contract?

Reveal the answer
  1. 2
  2. 1
  3. 0

For this input the result is 1. Newly enqueued children belong to the next level. Compare this independent fixture with the worked trace: The sample levels contain [1], [2,3], and [4,5,6]. Their sums are 1,5,15. Reading the initial queue length confines each inner loop to one level even as children are enqueued.

Go deeper

Common misconception: “Queue length is constant throughout traversal”

Newly enqueued children belong to the next level. The sample levels contain [1], [2,3], and [4,5,6]. Their sums are 1,5,15. Reading the initial queue length confines each inner loop to one level even as children are enqueued.

  1. Concrete transition: The sample levels contain [1], [2,3], and [4,5,6]. Their sums are 1,5,15. Reading the initial queue length confines each inner loop to one level even as children are enqueued.
  2. Independent second fixture: Input [1] produces 1. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input [1,null,2,null,3] produces 1,2,3. Newly enqueued children belong to the next level. The stated work bound is O(n) time · O(w) queue. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input [1,2,3,4,5,null,6] with [2,1,3]. Predict why their results are 1,5,15 and 2,4. Then change one legal value and explain whether the same invariant, newly enqueued children belong to the next level, still applies.

Connections

  • Level-Order BFS: Mental Model: Queue nodes and process exactly the current queue length to preserve level boundaries.
  • Challenge: Level-Order BFS: Parse the compact level-order binary tree, where null omits a node. Return the sum of each level from the root downward.
Reveal the Algorithm Atlas answer

1,5,15

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Level-Order BFS: When to Use It (courseId "algorithms", lessonId "algorithm.tree-level-order.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.tree-level-order.recognize
Goal: Newly enqueued children belong to the next level. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.tree-level-order.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.