Sum Root to Leaf Numbers

Medium

Company Tags

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number.

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

Example 1:

Input: root = [1,5,1,null,null,null,6]

Output: 131

Explanation:
The root to leaf path 1 -> 5 represents the number 15.
The root to leaf path 1 -> 1 -> 6 represents the number 116.
The sum of both the numbers is: 15 + 116 = 131.

Example 2:

Input: root = [1,2,1,9,2,3,4]

Output: 478

Explanation:
The root to leaf path 1 -> 2 -> 9 represents the number 129.
The root to leaf path 1 -> 2 -> 2 represents the number 122.
The root to leaf path 1 -> 1 -> 3 represents the number 113.
The root to leaf path 1 -> 1 -> 4 represents the number 114.
The sum the numbers is: 129 + 122 + 113 + 114 = 478.

Constraints:

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


Company Tags

Please upgrade to NeetCode Pro to view company tags.

Solution 1
Stuck? Get hints based on your code
||Ln 1, Col 1

root =