Sum Root to Leaf Numbers

Given the root of a binary tree where each node contains a single digit, return the total sum of all the numbers formed by root-to-leaf paths. Pattern focus: Preorder DFS (Root First). Carry the number formed so far as you move downward.

Input Format

root = binary tree root where each node value is a digit

Output Format

sum of all root-to-leaf numbers

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= node values <= 10^4
  • Input must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

root = [1,2,3]

Output:

25

Explanation:

The numbers are 12 and 13, so the sum is 25.

Example 2:

Input:

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

Output:

1026

Explanation:

The root-to-leaf numbers are 495, 491, and 40.

Loading...
Sum Root to Leaf Numbers - Binary Tree