MediumTreeDepth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary tree in which every node holds a single digit between 0 and 9. Each root-to-leaf path spells out a number: read the digits from the root down to the leaf and concatenate them, so a path 1 -> 2 -> 3 represents the number 123.

Return the sum of all the numbers formed by the root-to-leaf paths. The problem guarantees the total fits within a 32-bit signed integer.

A leaf is a node with no children.

Example 1

Input: root = [1,2,3]

Output: 25

The path 1 -> 2 gives 12 and 1 -> 3 gives 13, so the total is 25.

Example 2

Input: root = [4,9,0,5,1]

Output: 1026

The paths spell 495, 491, and 40, which add up to 495 + 491 + 40 = 1026.

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • 0 <= Node.val <= 9
  • The depth of the tree will not exceed 10.

After the pattern

Now solve one you haven't seen.

Total of the Menu Paths is our own problem on the technique behind Sum Root to Leaf Numbers: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free