Sum Root to Leaf Numbers — LeetCode 129 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#129
Reading time
3 min

The problem

You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number.

Example

Input
root = [1,2,3]
Output
25
Explanation
The root-to-leaf path 1->2 represents the number 12.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        def dfs(root, s):
            if root is None:
                return 0
            s = s * 10 + root.val
            if root.left is None and root.right is None:
                return s
            return dfs(root.left, s) + dfs(root.right, s)

        return dfs(root, 0)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(\log n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 129. Sum Root to Leaf Numbers is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 129. Sum Root to Leaf Numbers?
LeetCode 129. Sum Root to Leaf Numbers is rated Medium on LeetCode.
What is the time complexity of LeetCode 129. Sum Root to Leaf Numbers?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 129. Sum Root to Leaf Numbers?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 129. Sum Root to Leaf Numbers cover?
LeetCode 129. Sum Root to Leaf Numbers is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview