Intuition
Carry the number formed so far down each path. At each node the running number becomes cur*10 + node.val. When you reach a leaf, that running value is a complete root-to-leaf number; sum those over all leaves.
Explanation
Idea
Each root-to-leaf path spells a decimal number: descending one level appends a digit, i.e. multiply the number so far by 10 and add the new node's value. A DFS that threads this cur value downward hits every leaf with its finished number; summing those gives the answer.
Algorithm
dfs(node, cur):
- If
nodeis null, return 0. cur = cur * 10 + node.val.- If
nodeis a leaf, returncur. - Otherwise return
dfs(left, cur) + dfs(right, cur).
Start with dfs(root, 0).
Worked example: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Paths: 4→9→5 = 495, 4→9→1 = 491, 4→0 = 40. Sum = 1026.
Complexity
- Time: O(n).
- Space: O(h) recursion depth.
Implementation
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode node, int cur) {
if (node == null) {
return 0;
}
cur = cur * 10 + node.val;
if (node.left == null && node.right == null) {
return cur;
}
return dfs(node.left, cur) + dfs(node.right, cur);
}
}