MediumTreeDepth-First SearchBinary Tree

Sum Root to Leaf Numbers

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now