↓Skip to main content
  1. LeetCode/

LeetCode 129: Sum Root to Leaf Numbers

·1 min· ·
LeetCode Medium Tree Depth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-18

  • Submissions: Accepted ×2 → Runtime Error → Accepted

Approach
#

Each level adds a digit: num = num * 10 + node.val (Tree Template 1). At a leaf the path’s number is complete and joins the total. Integer arithmetic beats building strings.

My Attempts
#

In 2024 one version missed nodes with a single child: it recursed into None and read node.left, failing on [9, 9] (left child only).

Solution
#

class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        def dfs(node, num):
            if not node:
                return 0
            num = num * 10 + node.val
            if not node.left and not node.right:
                return num
            return dfs(node.left, num) + dfs(node.right, num)
        return dfs(root, 0)

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • With one child, the empty side returns 0 instead of reading None.

Interview Explanation
#

Recursing down, I multiply the current number by 10 and add the node’s value, return it at a leaf, and sum both sides. Time O(n).

Related

LeetCode 113: Path Sum II
·2 mins
LeetCode Medium Backtracking Tree Depth-First-Search Binary-Tree
LeetCode 113 note: backtrack with the current path and store a copy at a leaf whose total matches; values can be negative, so no early pruning
LeetCode 236: Lowest Common Ancestor of a Binary Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Tree Binary-Lifting
LeetCode 236 note: recursion returns whichever of p or q a subtree contains; finding something on both sides means they split here, so this node is the LCA
LeetCode 337: House Robber III
·2 mins
LeetCode Medium Dynamic-Programming Tree Depth-First-Search Binary-Tree
LeetCode 337 note: tree DP where each node returns the best (rob it, skip it) pair; not robbing alternate levels
LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 230: Kth Smallest Element in a BST
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 230 note: a BST’s in-order traversal is ascending, so stop an iterative in-order walk at the k-th node