Python 0404.py
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def deeper(node, isLeft):
if not node:
return 0
if not node.left and not node.right:
return node.val if isLeft else 0
return deeper(node.left, True) + deeper(node.right, False)
return deeper(root, False)
Difficulty
and has an acceptance rate of about 63% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- 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 method sumOfLeftLeaves that computes the sum of all left-leaf node values in a binary tree. The algorithm employs a nested helper function named deeper to perform a depth-first traversal, distinguishing between left and right children via a boolean flag. The result is obtained by invoking deeper on the root node with the flag set to False, indicating that the root itself is not considered a left child.
Key Steps
The core logic resides in the deeper function. The first conditional checks whether the current node reference is None. In that case the function returns 0, effectively terminating the recursion for empty subtrees.
if not node:
return 0
The next conditional determines whether the node is a leaf by confirming the absence of both left and right children. If the node is a leaf, the function returns its value only when the isLeft flag is True; otherwise it contributes 0 to the sum.
if not node.left and not node.right:
return node.val if isLeft else 0
When the node is not a leaf, the function proceeds to explore both subtrees. It recursively calls itself on the left child with the flag set to True, marking that child as a left descendant, and on the right child with the flag set to False. The results of the two recursive calls are added together and returned.
return deeper(node.left, True) + deeper(node.right, False)
The outer method simply forwards the root node to deeper with isLeft set to False, because the root cannot be a left leaf by definition.
return deeper(root, False)
Edge Cases
The recursion gracefully handles an empty tree because the initial call to deeper receives None as the node argument, triggering the first conditional and returning 0.
When the tree consists of a single node, that node is a leaf but not a left leaf; the isLeft flag remains False, causing the leaf-value branch to yield 0.
If a left leaf appears deep within the tree, the boolean flag propagates correctly through each recursive step, ensuring that only leaves reached via a left-child link contribute their values.
A tree that contains only right children also results in a sum of 0 because every leaf is reached with isLeft equal to False.
Performance Optimizations
The algorithm leverages tail-recursive style calls without allocating auxiliary data structures such as stacks or queues, thereby minimizing memory overhead during traversal. By returning early for None nodes and leaf nodes, the function avoids unnecessary deeper recursion into empty subtrees. The use of a single boolean parameter to indicate left-child status eliminates the need for additional state tracking or complex condition checks, keeping each recursive invocation lightweight. The direct addition of the two recursive results eliminates intermediate variables, reducing the number of temporary objects created during execution.
ELI5 - Simplified Explanation
Imagine a giant tree standing upside down with many branches reaching out. Each branch connects to smaller branches until you reach the very end, which is a leaf. Some leaves hang on the left side of a branch, and others hang on the right side. The goal is to find all the special leaves that are hanging specifically on the left side and add up the numbers written on them.
The code starts at the very top of the tree, which is called the root. It walks down every path to see where the leaves are hiding. When it arrives at a leaf, it checks if that leaf is sitting on the left side of its parent branch. If the leaf is indeed on the left, it remembers the number. If the leaf is on the right side, the code ignores that number and keeps looking. It does this by visiting every single branch one by one until it has checked every corner of the tree. Once it finishes looking at every part, it provides the total sum of all those left-side leaves that were found along the way.
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | C | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, 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 | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1973: Count Nodes Equal to Sum of Descendants
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
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