Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
1
2
3
4
5
4
/ \
9 0
/ \
5 1
1
2
3
4
5
6
7
Input: root = [4,9,0,5,1]
Output: 1026
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.
Therefore, sum = 495 + 491 + 40 = 1026.
To solve this problem, we traverse the entire binary tree and compute numbers for each root-to-leaf path. For every node in the tree, the number represented by the path extending down to that node can be calculated by multiplying the sum from its parent node by 10 and adding the value of the current node.
The traversal can be done using either a depth-first search (DFS) or breadth-first search (BFS). DFS is commonly used for this type of problem since we need to follow each path to its leaves.
Method 1 - Recursive - Calculating Current Number and Sum#
Here is the approach:
At each recursive call, pass the current sum calculated so far.
For every node, calculate the new sum as current_sum * 10 + node.val.
If the node is a leaf, add its value to the total sum.
Recursively process the left and right child nodes.
Edge case: If the tree is empty (root == null), return 0.
publicintsumNumbers(TreeNode root) {
return dfs(root, 0, 0);
}
publicintdfs(TreeNode node, int num, int sum) {
if (node ==null) {
return sum;
}
num = num * 10 + node.val;
// leafif (node.left==null&& node.right==null) {
sum += num;
return sum;
}
// left subtree + right subtree sum = dfs(node.left, num, sum) + dfs(node.right, num, sum);
return sum;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defsumNumbers(self, root: Optional[TreeNode]) -> int:
defdfs(node: Optional[TreeNode], num: int, sum: int) -> int:
ifnot node:
return sum # Base case: empty tree num = num *10+ node.val
ifnot node.left andnot node.right:
sum += num;
return sum
# Recur for left and right children sum = dfs(node.left, num, sum) + dfs(node.right, num, sum)
return dfs(root, 0, 0)
⏰ Time complexity: O(n). Every node is visited once, so the time complexity is linear concerning the number of nodes.
🧺 Space complexity: O(h). The space complexity is determined by the recursion stack depth, which is proportional to the height h of the binary tree. In the worst case, a skewed binary tree gives h = n.