Sum Root to Leaf Numbers
LeetCode 129 · Medium · solution, intuition & step-by-step walkthrough
Carry the path's digits; add at leaves.
This is how I solved Sum Root to Leaf Numbers (LeetCode 129), a medium problem from the Root-to-Leaf Paths pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Each root-to-leaf path spells a number. Build the digits as you go down (here as a string), and when you hit a leaf, add that number to the total.
Approach
- 1
dfs(node, path): append node.val to the path.
- 2
At a leaf, add int(path) to the sum.
- 3
Otherwise recurse into both children.
How I solved it
DFS building digitsPythonO(n·h) time
class Solution:
def sumNumbers(self, root):
self.total = 0
def dfs(node, path):
if node is not None:
path += str(node.val)
if node.left is None and node.right is None:
self.total += int(path)
return
dfs(node.left, path)
dfs(node.right, path)
dfs(root, "")
return self.totalSum Root to Leaf Numbers — FAQ
What is the intuition behind Sum Root to Leaf Numbers?
Each root-to-leaf path spells a number. Build the digits as you go down (here as a string), and when you hit a leaf, add that number to the total.
How do you solve Sum Root to Leaf Numbers (LeetCode 129)?
1. dfs(node, path): append node.val to the path. 2. At a leaf, add int(path) to the sum. 3. Otherwise recurse into both children.
What is the time and space complexity of Sum Root to Leaf Numbers?
Time: O(n · h) with strings (O(n) with path·10 + val). Space: O(h). (Accepted approach: DFS building digits.)
What are common mistakes in Sum Root to Leaf Numbers?
path·10 + val avoids string building.