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-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.Find the total sum of all root-to-leaf numbers.
For example,
1
2
3 1
/ \
2 3The root-to-leaf path
1->2represents the number12.
The root-to-leaf path1->3represents the number13.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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-sum-root-to-leaf-numbers/
