Sum of Root To Leaf Binary Numbers (LeetCode 1022): Solution and Explanation

Easy
Tree
Depth First Search
Binary Tree

Every node in the tree holds a 0 or a 1, and each root-to-leaf path spells a binary number with the root as the most significant bit. Add up the numbers from all paths.

Intuition

Reading a binary number left to right works like a shift register. Each new bit pushes everything read so far one place to the left, which doubles it, and then the bit fills the empty last place.

Walking down the tree reads bits in exactly that order. So if you know the value of the path down to a parent, the value at its child is parent_value * 2 + child_bit. No strings or powers of two are needed.

A DFS can carry that running value down the tree. When it reaches a leaf, the path is finished and its value is the number for that path. Every inner node just adds up what its two subtrees report.

Approach: DFS carrying the running value

  1. Call dfs(root, 0).
  2. In dfs(node, cur), return 0 if the node is missing.
  3. Shift in the node's bit: cur = cur * 2 + node.val.
  4. If the node is a leaf, return cur: that is one complete path's number.
  5. Otherwise return dfs(node.left, cur) + dfs(node.right, cur).

Step-by-step example

root = [1,0,1,0,1,0,1]
  1. At the root, cur = 0 * 2 + 1 = 1.
  2. Go left to 0: cur = 1 * 2 + 0 = 2. Its leaves give 2 * 2 + 0 = 4 (100) and 2 * 2 + 1 = 5 (101), so this subtree returns 9.
  3. Go right to 1: cur = 1 * 2 + 1 = 3. Its leaves give 6 (110) and 7 (111), so this subtree returns 13.
  4. The root returns 9 + 13 = 22.

Code: Python, Java, C++

1class Solution:
2    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
3        def dfs(node, cur):
4            if not node:
5                return 0
6            cur = cur * 2 + node.val
7            if not node.left and not node.right:
8                return cur
9            return dfs(node.left, cur) + dfs(node.right, cur)
10        return dfs(root, 0)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does a constant amount of work.

Space

O(h)

The recursion stack holds one frame per node on the current path, so it grows with the tree height h.

Other approaches

Iterative DFS with a stack of (node, value) pairs (time O(n), space O(h))

Push the root with value 0. Pop a pair, compute the node's value, add it to the total at a leaf, and push the children with the new value. It avoids recursion limits on deep trees.

BFS with (node, value) pairs (time O(n), space O(w))

The same running-value idea works level by level with a queue, adding each leaf's value as it is dequeued.

Build path strings (time O(n h), space O(h))

Collect each path's bits as a string and convert it at the leaf. It works, but it copies a string per step and does extra parsing.

Common mistakes

  • Adding a value at nodes with only one child. Only leaves end a path; a node with one missing child still continues through the other.
  • Returning cur for a missing child instead of 0, which counts a path that does not end at a leaf.
  • Reading the bits in the wrong order. The root is the most significant bit, so the value is shifted left before each new bit, not after.
  • Sharing one mutable value across branches without undoing it. Passing cur as a parameter keeps each branch's value separate.

Frequently asked questions

Why multiply by 2?

In base 2, adding a digit on the right shifts all existing digits one place left, which doubles their value. The new bit then adds 0 or 1.

Can I use bit operations instead?

Yes. (cur << 1) | node.val is the same as cur * 2 + node.val for these values.

What about leading zeros?

They do no harm. A path starting with 0 just keeps cur at 0 until the first 1 appears, exactly like a binary number with leading zeros.