简繁EN

LeetCodeNo. 102

[LeetCode with Python] 129. Sum Root to Leaf Numbers

Contents

Problem

Problem page: https://leetcode.com/problems/sum-root-to-leaf-numbers/
Topics: Tree, Depth-first Search
Difficulty: Medium
Similar problems: (E) Path Sum, (H) Binary Tree Maximum Path Sum

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

1
2
3
  1
/ \
2 3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.


Analysis

Each path from the root to a leaf represents a number. Find all those numbers and add them up.
A search algorithm can find a feasible solution or all the solutions. If you only need one solution, you can use depth-first search (DFS) or breadth-first search (BFS). One solution isn't enough for this sum, though. When searching for all the solutions, there are generally two ways to use recursion: bottom-up and top-down (my own names for them, haha).
Here, working bottom-up means that once the recursion reaches a leaf, we add the numbers returned by the recursive calls on the left and right subtrees as the stack unwinds.
This solution uses the distributive property of multiplication. Without it, each time we "return", we'd have to pass a list of numbers back up one level, and the closer we got to root, the longer the list would be. Or we could keep a running total in an instance variable and, whenever we reach a leaf, add the value of the path to that leaf to the total.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def doSumNumbers(self, root, val):
if None == root.left and None == root.right:
return val * 10 + root.val
left = 0
right = 0
if None != root.left:
left = self.doSumNumbers(root.left, val * 10 + root.val)
if None != root.right:
right = self.doSumNumbers(root.right, val * 10 + root.val)
return left + right

# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
if None == root:
return 0
return self.doSumNumbers(root, 0)

Article link: https://xnerv.wang/en/leetcode-sum-root-to-leaf-numbers/