Deepest Leaves Sum

Medium

Topics
TreeBFSDFS

Given the root of a binary tree, return the sum of values of its deepest leaves.

Example 1

74251368
deepest level
Only the leaves on the single deepest level count, so shallower leaves are excluded. A level-order walk needs no depth bookkeeping at all: the sum of the last level it produces is the answer, 15.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Example 2

92717461835
deepest level
Input:  root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19

Constraints

  • 1 <= number of nodes <= 10^4
  • 1 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

We want the sum of the values at the greatest depth. A DFS tracking depth works: find the maximum depth, then sum the nodes at it — either in two passes, or in one by resetting the total whenever a deeper level appears.

A level-by-level BFS makes it almost free. Process the tree one complete level at a time and, at the start of each level, reset the running total. When the queue empties, the total holds whatever the last level contributed — no depth bookkeeping and no second pass.

The mechanism that makes "one complete level at a time" work is capturing len(queue) before the inner loop. That count is exactly the current level's width, so the loop consumes this level and enqueues the next without the two mixing.

Approach

  1. Queue with the root.
  2. While the queue is non-empty: reset the total, then process exactly len(queue) nodes, adding values and enqueuing children.
  3. Return the total.

Dry Run

tree        1
           / \
          2   3
         / \   \
        4   5   6
       /
      7

level 0  [1]        total = 1
level 1  [2,3]      total reset, = 5
level 2  [4,5,6]    total reset, = 15
level 3  [7]        total reset, = 7
queue empty

answer 7

The reset at the top of each level is the whole trick: every level overwrites the previous total, so the last one to run is the one that survives.

Complexity

  • Time — O(n): each node enqueued and dequeued once.
  • Space — O(w): the queue holds at most one level, where w is the widest level — up to n/2 for a complete tree. A DFS would be O(h) instead, which is better on a wide shallow tree and worse on a deep thin one.

Common Pitfalls

  • Not capturing the level size before the inner loop. Reading len(queue) inside it mixes levels and the reset lands in the wrong place.
  • Accumulating across levels instead of resetting, which sums the whole tree.
  • Resetting after the level rather than before, which leaves the total at 0.
  • Assuming the deepest level is a single node. It can hold several, and all of them count.
  • Not guarding an empty tree, though the constraints here promise at least one node.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def deepestLeavesSum(self, root):
        from collections import deque
        q = deque([root]); total = 0
        while q:
            total = 0
            for _ in range(len(q)):
                n = q.popleft(); total += n.val
                if n.left: q.append(n.left)
                if n.right: q.append(n.right)
        return total
Asked at Myntra
SensAI
Beta
Tap the mic to stop voice mode