22 · Tree Recursion

#129 Sum Root to Leaf Numbers

Mediumsolve on LeetCode ↗

frequently reported atMetaGoogleAmazonMicrosoft

the problem

In plain words

Every node holds one digit, 0 to 9. Reading a root-to-leaf path from top to bottom spells a number: 1 → 2 → 3 spells 123. Return the sum of the numbers spelled by all root-to-leaf paths. The answer fits in a 32-bit int.

in root = [1,2,3]

out 25

12 + 13.

in root = [4,9,0,5,1]

out 1026

495 + 491 + 40.

  • 1 ≤ number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 9
  • Depth of the tree ≤ 10

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #112
      Path Sum
      Easyin Tree Recursion
    2. #1448
      Count Good Nodes in Binary Tree
      Mediumin Tree Recursion
    3. #113
      Path Sum II
      Mediumin Tree Recursion