Sum Root to Leaf Numbers

Medium#129top-down

You get the root of a binary tree whose nodes hold digits from 0 to 9. Each path from the root down to a leaf spells a number: 1 → 4 → 6 is 146. Return the sum of all these numbers. Our tree: 2 with children 7 and 5; 7 has children 3 and 0, and 5 has only a right child 8. The paths spell 273, 270, 258 — the answer is 801.

input
root: a binary tree of digits, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
The sum of the numbers that the paths from the root down to each leaf (a node with no children) spell out, digit by digit: the path 4 → 0 → 7 is 407.
constraints
  • 1 ≤ the number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 9
  • the depth of the tree ≤ 10
  • the answer ≤ 2³¹ − 1
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
function sumNumbers(root) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.