Ctrl K

Digit Branch Totals

Medium
Every node of the binary tree root holds a single digit. Each path from the root down to a leaf spells out a number, read top to bottom. For example, the path 5 → 0 → 4 is the number 504. Return the sum of the numbers spelled by all such paths. A leaf is a node with no children. The answer is guaranteed to fit in a 32-bit integer.
Example 1
root=tree_node([3, 1, 8]) → 69

Two branches: 3 → 1 reads as 31 and 3 → 8 reads as 38, so the total is 31 + 38 = 69.

Example 2
root=tree_node([2, 0, None, 7, 5]) → 412

The root has only a left child 0, which has two leaves. The numbers 207 and 205 add up to 412.

Example 3
root=tree_node([6]) → 6

The root is itself a leaf, so the only number is 6.

Constraints
  • The tree has between 1 and 1000 nodes
  • 0 ≤ Node.val ≤ 9
  • The tree is at most 10 levels deep
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumFlip a Tree Along Its Left Spine Medium
loading Python…
Input
root=tree_node([3, 1, 8])
Expected
69

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.