#129

Sum Root to Leaf Numbers

Medium
TreeDepth-First SearchBinary TreeDepth-First SearchRecursionTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution uses Depth-First Search (DFS) to traverse the tree while maintaining the current number formed by the path. This avoids unnecessary recalculations and efficiently sums the numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a recursive DFS function that takes the current node and the number formed so far.
  2. 2Step 2: If the current node is a leaf, return the current number.
  3. 3Step 3: Otherwise, recursively call the function for the left and right children, updating the current number.
solution.py16 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def sumNumbers(self, root: TreeNode) -> int:
9        def dfs(node, current_number):
10            if not node:
11                return 0
12            current_number = current_number * 10 + node.val
13            if not node.left and not node.right:
14                return current_number
15            return dfs(node.left, current_number) + dfs(node.right, current_number)
16        return dfs(root, 0)

Complexity note: The time complexity is O(n) since we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Understanding how to traverse a tree recursively is crucial for solving tree-related problems.
  • 2Recognizing leaf nodes is essential for determining when to sum the current number.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.