/129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

Medium
Trees69.7% acceptance

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

Example 1

Input: TreeNode(7, TreeNode(2, None, TreeNode(6)), TreeNode(5))

Output: 726 + 75 = 801

Explanation: Paths: 7->2->6 forms 726, 7->5 forms 75. Sum = 801.

Example 2

Input: TreeNode(3, TreeNode(1, TreeNode(4)), TreeNode(9, None, TreeNode(8)))

Output: 314 + 398 = 712

Explanation: Paths: 3->1->4 forms 314, 3->9->8 forms 398. Sum = 712.

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= node.value <= 9
  • Tree depth <= 10
Python (current runtime)

Case 1

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

Expected: 20 + 231 = 251

Case 2

Input: TreeNode(8, TreeNode(7, None, TreeNode(5)), None)

Expected: 875

Case 3

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

Expected: 19 + 102 + 103 = 224