Problem 129

Abstract / Summary

Find the total of all numbers formed from root to leaf paths in a binary tree with digits as node values

Note

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

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
28 lines | 649 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • 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 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.

written by openai gpt

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.

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 = 6 | μ = 6.00 | σ = 1.41

Complexity Analysis

not analyzed yet

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++ 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++
55 links | 38 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Sum Root to Leaf Numbers - Coding Interview Question - Leetcode 129'
NeetCode 6 mins
Sum Root to Leaf Numbers - Coding Interview Question - Leetcode 129
YouTube video 'Sum Root to Leaf Numbers | Leetcode - 129 | Google | Microsoft | Meta | Explanation | Live Coding'
codestorywithMIK 13 mins
Sum Root to Leaf Numbers | Leetcode - 129 | Google | Microsoft | Meta | Explanation | Live Coding
YouTube video 'Sum of Root To Leaf Binary Numbers | Simple Approach | Dry Run | Leetcode 1022 | MIK'
codestorywithMIK 15 mins
Sum of Root To Leaf Binary Numbers | Simple Approach | Dry Run | Leetcode 1022 | MIK
YouTube video 'Sum Root to Leaf Numbers || Leetcode 129 || 2 Variant Questions Big Tech Actually Asks'
Coding with Minmer 28 mins
Sum Root to Leaf Numbers || Leetcode 129 || 2 Variant Questions Big Tech Actually Asks
YouTube video 'Sum Root to Leaf Numbers | LeetCode 129 | C++, Java, Python'
Knowledge Center 16 mins
Sum Root to Leaf Numbers | LeetCode 129 | C++, Java, Python
YouTube video '129. Sum Root to Leaf Numbers || Morris Traversal - Preorder + Inorder'
Aryan Mittal 34 mins
129. Sum Root to Leaf Numbers || Morris Traversal - Preorder + Inorder
YouTube video 'SUM ROOT TO LEAF NUMBERS | LEETCODE 129 | PYTHON DFS SOLUTION'
Cracking FAANG 9 mins
SUM ROOT TO LEAF NUMBERS | LEETCODE 129 | PYTHON DFS SOLUTION
YouTube video 'Sum Root To Leaf Numbers - LeetCode 129 - JavaScript'
AlgoJS 6 mins
Sum Root To Leaf Numbers - LeetCode 129 - JavaScript
YouTube video 'Sum Root to Leaf Numbers | Leetcode 129 | Live coding session 🔥🔥🔥🔥'
Coding Decoded 8 mins
Sum Root to Leaf Numbers | Leetcode 129 | Live coding session 🔥🔥🔥🔥
YouTube video 'Sum Root to Leaf Numbers #leetcode #topinterview150'
Deepti Talesra 10 mins
Sum Root to Leaf Numbers #leetcode #topinterview150
YouTube video '129. Sum Root to Leaf Numbers || Java || Leetcode || Hindi'
Coding Sphere 8 mins
129. Sum Root to Leaf Numbers || Java || Leetcode || Hindi
YouTube video '129 || Sum Root to Leaf Numbers II || C++ || Leetcode Daily Challenge'
CodeFreaks 13 mins
129 || Sum Root to Leaf Numbers II || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #2156: Feb 24, 2026 - 1022. Sum of Root To Leaf Binary Numbers'
Programming Live with Larry 4 mins
Daily Leetcode #2156: Feb 24, 2026 - 1022. Sum of Root To Leaf Binary Numbers
YouTube video 'Daily Leetcode #1476: Apr 15, 2024 - 129. Sum Root to Leaf Numbers'
Programming Live with Larry 6 mins
Daily Leetcode #1476: Apr 15, 2024 - 129. Sum Root to Leaf Numbers
YouTube video '129. Sum Root to Leaf Numbers | April | Java | C++'
Mayur Programming Club 13 mins
129. Sum Root to Leaf Numbers | April | Java | C++
YouTube video 'sum root to leaf numbers | sum root to leaf numbers leetcode | leetcode 129 | medium'
Naresh Gupta 8 mins
sum root to leaf numbers | sum root to leaf numbers leetcode | leetcode 129 | medium
YouTube video 'Daily Leetcode #1078: Mar 14, 2023 - 129. Sum Root to Leaf Numbers'
Programming Live with Larry 5 mins
Daily Leetcode #1078: Mar 14, 2023 - 129. Sum Root to Leaf Numbers
YouTube video '129. Sum Root to Leaf Numbers | LEETCODE BINARY TREE | LEETCODE MEDIUM | CODE EXPLAINER'
code Explainer 5 mins
129. Sum Root to Leaf Numbers | LEETCODE BINARY TREE | LEETCODE MEDIUM | CODE EXPLAINER
YouTube video '129. Sum Root to Leaf Numbers | Leetcode | Binary Tree | DSA'
Coding with Tamilarasan 13 mins
129. Sum Root to Leaf Numbers | Leetcode | Binary Tree | DSA
YouTube video 'Daily Leetcode #582: Nov 03, 2021 - 129. Sum Root to Leaf Numbers'
Programming Live with Larry 8 mins
Daily Leetcode #582: Nov 03, 2021 - 129. Sum Root to Leaf Numbers
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

30 solutions   August 15, 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