129. Sum Root to Leaf Numbers ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Binary Tree
, Depth-First Search (DFS)
, Backtracking
, Math
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. For example:
The root-to-leaf path 1 -> 2 -> 3
represents the number 123
.
Task:
Return the total sum of all root-to-leaf numbers.
A leaf node is a node with no children.
๐น Example 1:
Input:
Output:
Explanation:
The root-to-leaf path 1 -> 2
represents the number 12
.
The root-to-leaf path 1 -> 3
represents the number 13
.
Total sum: 12 + 13 = 25
.
๐น Example 2:
Input:
Output:
Explanation:
The root-to-leaf path 4 -> 9 -> 5
represents the number 495
.
The root-to-leaf path 4 -> 9 -> 1
represents the number 491
.
The root-to-leaf path 4 -> 0
represents the number 40
.
Total sum: 495 + 491 + 40 = 1026
.
The number of nodes in the tree is in the range [1, 1000]
.
0 <= Node.val <= 9
The depth of the tree will not exceed 10
.
To compute the sum of all root-to-leaf numbers:
Use Depth-First Search (DFS) or Backtracking to traverse the binary tree.
Pass the current accumulated value (a running total) down the recursion stack.
When a leaf node is reached, add the accumulated value to the result.
DFS Traversal:
Start from the root with an initial currentSum
of 0
.
As you traverse, update currentSum
by multiplying it by 10
and adding the node's value.
Leaf Node Check:
If the current node is a leaf (no children), return the currentSum
.
Recursive Calls:
Recurse on the left and right children, passing the updated currentSum
.
Combine Results:
Add up the results from the left and right subtrees to get the total sum.
O(n): Each node is visited once.
O(h): Where h
is the height of the tree (due to recursion stack).
How would you implement an iterative solution for this problem using a stack or queue?
Could you optimize the memory usage further in the recursive solution?