You are given a binary tree. Write a function to find the "sum of all root-to-leaf paths". Please each root-to-leaf path represents a number. For example, 1->2->3 represents the number 123, write a function that solves this problem, and explain your recursive DFS algorithm.
Assistant
We are given a binary tree. Each root-to-leaf path represents a number: the digits are the node values along the path.
We need to sum all such numbers.
Approach:
We can do a DFS (preorder) traversal. At each node, we keep the current number formed by the path from the root to this node.
When we reach a leaf node (both children are null), we add the current number to the total sum.
Steps:
Start at the root with current number = 0.
For each node, update current number = current number * 10 + node.val.
If the node is a leaf, return the current number.
Otherwise, recursively compute the sum from left and right subtrees (if they exist) and return their sum.
Alternatively, we can pass the current number as a parameter and accumulate the sum when we hit a leaf.
Let's write a recursive helper function:
def dfs(node, current):
if node is None:
return 0
code
current = current * 10 + node.val
# If leaf
if node.left is None and node.right is None:
return current
# Otherwise, sum the results from left and right
left_sum = dfs(node.left, current) if node.left else 0
right_sum = dfs(node.right, current) if node.right else 0
return left_sum + right_sum
Then the main function:
def sumNumbers(root):
return dfs(root, 0)
However, note that the problem says "binary tree", not necessarily a full tree, so we must handle null children.
Let's test with example:
Tree: [1,2,3]
Start at root (1): current = 0*10+1 = 1.
Then, since it's not a leaf, we call dfs on left (2) and right (3).
For left (2): current = 1*10+2 = 12. Then it's a leaf? Wait, node 2 has no children? Actually in the example, 2 is a left child of 1 and has no children? The example tree: 1 has left child 2 and right child 3. 2 and 3 are leaves. So yes, for node 2: left_sum = 0, right_sum = 0? Actually, we check: node.left and node.right are both None? Yes, so it returns current=12.
For right (3): current = 1*10+3 = 13. Leaf, returns 13.
Start at 4: current = 4.
Then call left (9) with current=4, and right (0) with current=4.
For node 9: current = 4*10+9 = 49.
Then call left (5) with current=49 and right (1) with current=49.
code
For node 5: current = 49*10+5 = 495. Leaf -> return 495.
For node 1: current = 49*10+1 = 491. Leaf -> return 491.
So node 9 returns 495+491 = 986.
For node 0: current = 4*10+0 = 40. Leaf? It has no children? In the tree, 0 is a leaf? Yes, because it has no children. So returns 40.
Then root returns 986+40 = 1026.
Correct.
Implementation:
We assume the tree node has attributes: val, left, right.
Edge: if root is None, return 0.
Let's code accordingly.
To solve this problem, we need to compute the sum of all numbers formed by root-to-leaf paths in a binary tree, where each path represents a number with digits corresponding to node values from root to leaf.
Approach
We use a recursive depth-first search (DFS) to traverse every root-to-leaf path. During traversal, we maintain the current number formed by the path so far. When we reach a leaf node, we add the current number to the total sum. The key idea is to pass the accumulated number down the recursion, updating it by multiplying the previous value by 10 and adding the current node's value at each step.
Algorithm
Base Case: If the current node is None, return 0.
Update Current Number: current = current * 10 + node.val.
Leaf Check: If both left and right children are None (leaf node), return current.
Recursive Sum: Otherwise, recursively compute sums from left and right subtrees (if they exist) and return their sum.
Complexity
Time Complexity: O(N), where N is the number of nodes (each node visited once).
Space Complexity: O(H), where H is the tree height (recursion stack space, worst-case O(N) for skewed tree).
Solution Code
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sumNumbers(root: TreeNode) -> int:
def dfs(node, current):
if not node:
return 0
current = current * 10 + node.val
if not node.left and not node.right:
return current
left_sum = dfs(node.left, current) if node.left else 0
right_sum = dfs(node.right, current) if node.right else 0
return left_sum + right_sum
return dfs(root, 0)
Explanation
Helper Function dfs:
Takes a node and the current accumulated number.
Updates current to include the node's value as the next digit.
If the node is a leaf, returns the fully formed number.
Otherwise, recursively processes left and right subtrees, passing the updated current, and sums their results.
Main Function sumNumbers:
Initializes DFS with current = 0 at the root.
Returns the total sum from all root-to-leaf paths.
Example Walkthrough:
For tree [1,2,3]:
Path 1->2: current = 0→1→12 (leaf) → contributes 12.
Path 1->3: current = 0→1→13 (leaf) → contributes 13.
Total = 12 + 13 = 25.
This approach efficiently traverses each path exactly once, building numbers incrementally and summing them at leaves.