Python 1022.py
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
leafs = []
def deeper(node, have):
if node:
have <<= 1
have += node.val
if node.left or node.right:
deeper(node.left, have)
deeper(node.right, have)
else:
leafs.append(have)
deeper(root, 0)
return sum(leafs)
Difficulty
and has an acceptance rate of about 73% (200k+ 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 with a single public method sumRootToLeaf. The method receives the root of a binary tree whose nodes contain binary digits (0 or 1) and returns the sum of the integer values represented by all root-to-leaf paths. Each path is interpreted as a binary number where the most significant bit is at the root. The algorithm traverses the tree depth-first, builds the numeric value incrementally, stores the completed values for leaf nodes, and finally aggregates them with Python’s built-in sum.
Key Steps
The core of the solution is the nested helper function deeper. It receives a node reference and an accumulator have that holds the binary value constructed so far.
def deeper(node, have):
if node:
have <<= 1
have += node.val
if node.left or node.right:
deeper(node.left, have)
deeper(node.right, have)
else:
leafs.append(have)
-
Node existence check - The guard
if node:ensures that the recursion stops when a null child is encountered, preventing attempts to access attributes on aNoneobject. -
Binary accumulation - The line
have <<= 1left-shifts the current value, effectively multiplying it by two, andhave += node.valadds the current node’s bit. This mirrors the process of appending a new binary digit to the right side of a number. -
Branching decision - The condition
if node.left or node.right:distinguishes internal nodes from leaves. When at least one child exists, the function recurses on both left and right subtrees, passing the updated accumulator. -
Leaf handling - When a node has no children, the accumulated binary value represents a complete root-to-leaf number. It is appended to the list
leafsfor later summation.
After the recursive traversal completes, the method returns the total of all collected leaf values:
deeper(root, 0)
return sum(leafs)
The initial call starts with an accumulator of zero, representing an empty binary prefix.
Edge Cases Handled
The implementation gracefully manages several edge conditions without explicit branching outside the main recursion:
-
Empty tree - If
rootisNone, the initial call todeeperimmediately fails theif node:guard, leavingleafsempty. The finalsum(leafs)therefore returns0, correctly representing the sum of an absent set of paths. -
Single-node tree - When the tree consists of only the root, the node has neither left nor right child. The recursion treats this node as a leaf, computes
haveasnode.val, appends it toleafs, and the sum returns that single value. -
Unbalanced trees - The depth-first recursion does not rely on any balance property. Whether the tree leans heavily to one side or contains long chains, each node is visited exactly once, and leaf detection (
node.left or node.right) works uniformly. -
Nodes with value zero - The binary accumulation correctly incorporates zero bits. The left-shift operation preserves the existing bits, and adding
0leaves the accumulator unchanged for that position, ensuring that leading zeros in a path do not affect the numeric result.
Performance Optimizations
The code exhibits several implicit optimizations that contribute to efficient execution:
-
In-place accumulation - By updating
havethrough bitwise left-shift and addition, the algorithm avoids constructing intermediate strings or lists to represent the binary path. This keeps memory usage low and leverages fast integer arithmetic. -
Tail-recursive style for leaf capture - The leaf values are stored only when a leaf is reached, eliminating the need to keep partial results for internal nodes. The list
leafstherefore contains at most one entry per leaf, minimizing storage overhead. -
Single traversal - The depth-first search visits each node exactly once, performing a constant amount of work per node (a shift, an addition, and a couple of attribute checks). This linear visitation pattern ensures that the total work scales directly with the number of nodes.
-
Built-in aggregation - Using Python’s native
sumfunction to combine the leaf values leverages a highly optimized C implementation, which is faster than a manual accumulation loop written in pure Python.
Overall, the solution combines a concise recursive structure with integer-centric operations, delivering a clear and performant approach to summing binary numbers represented by root-to-leaf paths.
ELI5 - Simplified Explanation
Imagine a tree made of branches that start at the top and spread out toward the ground. Each branch has a little number attached to it. The goal is to walk from the very top piece all the way down to the bottom tips, picking up numbers along the way to build a secret code.
The code starts at the top piece. It keeps track of the numbers gathered so far by sliding them over to make room for a new digit and then adding the new piece. Think of this like shifting blocks to make a longer train.
Every time the path hits a split, the code decides to explore both directions to see where they lead. If a branch keeps going, the code keeps walking and collecting numbers. When a branch reaches a tip where there is nothing else to follow, the code knows the secret path is finished. It puts that finished path into a list, almost like saving a completed puzzle piece in a box.
Once every single path from the top to the bottom tips has been walked, the code looks at all the finished pieces inside the box and puts them together to find the final total.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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 | Go | Rust | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1582: Special Positions in a Binary Matrix
- problem 2331: Evaluate Boolean Binary Tree
- problem 449: Serialize and Deserialize BST
- problem 894: All Possible Full Binary Trees
- problem 919: Complete Binary Tree Inserter
- problem 951: Flip Equivalent Binary Trees
- problem 2415: Reverse Odd Levels of Binary Tree
- problem 297: Serialize and Deserialize Binary Tree
- problem 834: Sum of Distances in Tree
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