Sum Root to Leaf Numbers

Medium

Description

Given a binary tree where each node contains a digit from 0-9, each root-to-leaf path represents a number. Return the total sum of all root-to-leaf numbers.

Examples

Input:root = [1,2,3]
Output:25
Explanation:

12 + 13 = 25

Input:[7,2,6,null,9]
Output:801
Explanation:

The tree has paths 7→2→9 (forming number 729) and 7→6 (forming number 76). The sum is 729 + 76 = 805.

Input:[5]
Output:5
Explanation:

This is a single node tree. The only root-to-leaf path is just the root node itself, which represents the number 5.

Constraints

  • 1 ≤ number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 9

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!