Sum Root to Leaf Numbers

MediumMathLinked ListTreeBinary TreeGraph

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:805
Explanation:

The root-to-leaf paths are 7->2->9 = 729 and 7->6 = 76, so the total is 729 + 76 = 805.

Input:[5]
Output:5
Explanation:

A single-node tree has one root-to-leaf path consisting only of 5, so the total is 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!