Breadth-First Search
Medium

Level Order Sum / Averages

Calculate the sum or average of nodes at each level.
Problem Understanding

Given a binary tree, we often need to aggregate data per level.

  • Goal: Calculate the Sum (or Average, or Max) of all node values for each individual level.
  • Example: Root 1 (Sum 1). Children 2, 3 (Sum 5). Grandchildren 4, 5, 6 (Sum 15).
Algorithm Strategy

We use standard BFS with a Queue.

  1. Level Loop: Maintain a size variable level_size = queue.length.
  2. Accumulator: Inside the level processing loop, reset a current_level_sum = 0.
  3. Process: As we dequeue nodes, add node.val to current_level_sum.
  4. Result: After the inner loop finishes (level complete), store or compare the sum.
Interactive Visualization
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep