The problem requires you to find the sum of all numbers formed from root to leaf paths in a binary tree. Each path from the root to a leaf forms a number by concatenating the values of the nodes. For example, if the path forms the numbers 1 -> 2 -> 3, the number is 123.
Given the root of a binary tree, return the total sum of all root-to-leaf numbers.
We will use Depth-First Search (DFS) to traverse the tree. As we traverse, we will maintain the current number formed by the nodes’ path. When we reach a leaf node, we will add this number to the total sum. The DFS approach can be implemented using recursion.
total_sum
as 0.dfs(node, current_number)
where node
is the current node, and current_number
is the number formed from the root to that node.None
, return 0 (this handles the base case for an empty subtree).current_number
as current_number * 10 + node.val
.current_number
to total_sum
.dfs
on the left and right subtrees and accumulate their results.total_sum
after traversing the entire tree.# 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: TreeNode) -> int:
def dfs(node, current_number):
if not node:
return 0
current_number = current_number * 10 + node.val
if not node.left and not node.right: # It's a leaf
return current_number
# Recursive case for left and right children
left_sum = dfs(node.left, current_number)
right_sum = dfs(node.right, current_number)
return left_sum + right_sum
return dfs(root, 0)
O(N)
, where N
is the number of nodes in the tree. We visit each node exactly once.O(H)
, where H
is the height of the tree. This space is used by the recursion stack. In the worst case (a skewed tree), the height of the tree can be N
, but in the best case of a balanced tree, the height is log(N)
.This solution efficiently traverses the tree and accumulates the required sums while handle base cases correctly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?