Sum Root to Leaf Numbers

Every node of a binary tree holds one digit from 0 to 9. Each root-to-leaf path spells a number by reading its digits from the root down (the path 1 -> 2 -> 3 spells 123). Return the sum of the numbers spelled by all root-to-leaf paths. A leaf is a node with no children.

30:00

Sum Root to Leaf Numbers
medium
Free written solution
Topics
Companies

Every node of a binary tree holds one digit from 0 to 9. Each root-to-leaf path spells a number by reading its digits from the root down (the path 1 -> 2 -> 3 spells 123). Return the sum of the numbers spelled by all root-to-leaf paths. A leaf is a node with no children.

Example 1:
Input: {"root":[1,2,3]}
Output: 25
Constraints:
  • The number of nodes in the tree is in the range [1,1000][1, 1000].

  • 0≤Node.val≤90 \leq \text{Node.val} \leq 9

  • The depth of the tree will not exceed 1010.

  • The answer fits in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3]}

Call dfs(root, 0). The tree has 3 nodes and 2 leaves; each leaf ends one number.

123

cur = cur * 10 + node.val

each step down shifts the digits left and appends one

cur = 0

numbers at the leaves

none yet

0

current node
path from root (digits of cur)
finished leaf
subtree sum returned
Variables
VariableValue
nodenull
cur-
total0
DepthFunction Call
Stack empty
0/7