Problem 404

Abstract / Summary

Find the total value of all left child leaves in a binary tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
11 lines | 381 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.11 | σ = 0.68

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
49 links | 34 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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