/129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

Medium
Trees69.7% acceptance

Given the root node of a binary tree where each node contains a digit from 0 to 9, compute the sum of all numbers formed by root-to-leaf paths. Each path forms a number by concatenating the digits from the root to the leaf. Return the total sum of all such numbers.

Example 1

Input: TreeNode(8, TreeNode(3, TreeNode(2), TreeNode(7)), TreeNode(5))

Output: 832+837+85=1754

Explanation: Paths: 8->3->2 (832), 8->3->7 (837), 8->5 (85). Sum = 832+837+85=1754.

Example 2

Input: TreeNode(6, TreeNode(1), TreeNode(4, None, TreeNode(9)))

Output: 61+649=710

Explanation: Paths: 6->1 (61), 6->4->9 (649). Sum = 61+649=710.

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= node.value <= 9
  • Tree depth <= 10
  • Input is a valid binary tree
Python (current runtime)

Case 1

Input: TreeNode(2, TreeNode(0, None, TreeNode(3)), TreeNode(1))

Expected: 203+21=224

Case 2

Input: TreeNode(9, TreeNode(5, TreeNode(1)), TreeNode(6, None, TreeNode(2)))

Expected: 951+962=1913

Case 3

Input: TreeNode(4, TreeNode(7), None)

Expected: 47

Case 4

Input: TreeNode(1, None, TreeNode(2, TreeNode(3), None))

Expected: 123