Python 0129.py
class Solution:
def deeper(self, root):
if not root:
return []
current = str(root.val)
if not root.left and not root.right:
return [ current ]
result = []
for i in self.deeper(root.left):
result.append(current + i)
for i in self.deeper(root.right):
result.append(current + i)
return result
def sumNumbers(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
all = self.deeper(root)
sum = 0
for i in all:
sum += int(i)
return sum
Difficulty
and has an acceptance rate of about 70% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class that solves the problem of summing all numbers formed by root-to-leaf paths in a binary tree. Each node contains a single digit, and a path from the root to a leaf represents a decimal number obtained by concatenating the digits along the path. The class contains two methods: deeper, which recursively collects the string representation of every root-to-leaf number, and sumNumbers, which converts those strings to integers and aggregates the total.
Core Functions
deeper
The deeper method performs a depth-first traversal of the tree. It first checks whether the current node reference is None. In that case it returns an empty list, which naturally terminates recursion for missing children.
if not root:
return []
When a node exists, its value is converted to a string and stored in current. This string serves as the prefix for all numbers that will be built from this node downward.
current = str(root.val)
If the node is a leaf-both left and right children are absent-the method returns a list containing only the current prefix. This handles the base case where a complete number has been formed.
if not root.left and not root.right:
return [ current ]
For internal nodes, the method initializes an empty list result. It then recursively calls itself on the left child, concatenating the returned suffixes to the current prefix and appending each combined string to result. The same process is repeated for the right child. This approach builds every possible root-to-leaf string without needing additional data structures to track the path.
result = []
for i in self.deeper(root.left):
result.append(current + i)
for i in self.deeper(root.right):
result.append(current + i)
Finally, the method returns the accumulated list of strings representing all numbers that originate from the current subtree.
return result
sumNumbers
The sumNumbers method acts as the public entry point. It begins by handling the edge case where the input tree is empty; in that scenario it returns 0 because there are no numbers to sum.
if not root:
return 0
It then invokes deeper to obtain the complete collection of root-to-leaf strings.
all = self.deeper(root)
A variable sum is initialized to zero. The method iterates over each string in the list, converts it to an integer, and adds it to sum. By converting each string exactly once, the implementation avoids repeated parsing and keeps the conversion cost proportional to the number of leaf paths.
sum = 0
for i in all:
sum += int(i)
The final accumulated value is returned as the answer.
return sum
Edge Cases Handled
The code explicitly checks for a None root, returning an empty list from deeper and zero from sumNumbers. This ensures that an empty tree does not cause a recursion error.
When a node is a leaf, the method returns a list containing only the node’s digit as a string. This base case guarantees that the recursion terminates correctly and that each leaf contributes exactly one number to the final sum.
Both left and right child references are examined independently. If either child is missing, the corresponding recursive call yields an empty list, and the loop that appends concatenated strings simply does not execute for that side. This gracefully handles trees that are skewed to one side.
Performance Optimizations
The implementation leverages recursion to traverse the tree in a depth-first manner, which naturally aligns with the structure of root-to-leaf paths. By constructing the string prefix at each node and passing it down, the code avoids the need for auxiliary stacks or explicit path containers.
String concatenation is performed only when extending a prefix with a child’s suffix, which limits the number of intermediate string objects created. The use of a list to collect results from each subtree allows the method to batch the concatenation work before returning to the caller, reducing the overhead of repeated list extensions.
Conversion from string to integer occurs only after all paths have been generated, ensuring that each leaf’s number is parsed a single time. This separation of concerns-first building the complete set of strings, then performing numeric conversion-prevents redundant parsing that could arise from interleaving conversion with traversal.
Overall, the design balances clarity with efficient use of recursion, string handling, and integer conversion, resulting in a solution that scales well with the size of the binary tree.
ELI5 - Simplified Explanation
Imagine a tree made of numbers growing upside down from the sky. Each piece of the tree holds a tiny number tag. To find the answer, the computer starts at the very top of the tree and walks down every single path it can find until it reaches the end of a branch.
As it walks down a branch, it keeps a backpack where it collects the numbers it finds along the way. When it reaches the very tip of a branch, it takes all the numbers out of the backpack and puts them in a row to make one big number.
The computer does this for every single path in the tree. Once it has a big list of all the numbers it made from those paths, it adds them all together into one giant pile. Think of it like gathering up treasure from the ends of different garden paths and counting everything up at the end so it knows the total amount.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | JS | C | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | Python, Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 112: Path Sum
- problem 124: Binary Tree Maximum Path Sum
- problem 988: Smallest String Starting From Leaf
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality