Skip to content

Commit ebbb522

Browse files
Sum Root to Leaf Numbers
1 parent 93ef5bf commit ebbb522

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

26.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
3+
Sum Root to Leaf Numbers
4+
------------------------
5+
6+
Solution
7+
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
8+
9+
An example is the root-to-leaf path 1->2->3 which represents the number 123.
10+
11+
Find the total sum of all root-to-leaf numbers.
12+
13+
Note: A leaf is a node with no children.
14+
15+
Example:
16+
17+
Input: [1,2,3]
18+
1
19+
/ \
20+
2 3
21+
Output: 25
22+
Explanation:
23+
The root-to-leaf path 1->2 represents the number 12.
24+
The root-to-leaf path 1->3 represents the number 13.
25+
Therefore, sum = 12 + 13 = 25.
26+
Example 2:
27+
28+
Input: [4,9,0,5,1]
29+
4
30+
/ \
31+
9 0
32+
/ \
33+
5 1
34+
Output: 1026
35+
Explanation:
36+
The root-to-leaf path 4->9->5 represents the number 495.
37+
The root-to-leaf path 4->9->1 represents the number 491.
38+
The root-to-leaf path 4->0 represents the number 40.
39+
Therefore, sum = 495 + 491 + 40 = 1026.
40+
41+
*/
42+
43+
class Solution {
44+
public:
45+
int sumNumbers(TreeNode* root) {
46+
return getSum(root, 0);
47+
}
48+
int getSum(TreeNode *node, int sum) {
49+
if (node == NULL) return 0;
50+
int current_sum = sum * 10 + node->val;
51+
if (node->left == NULL && node->right == NULL) return current_sum;
52+
return getSum(node->left, current_sum) + getSum(node->right, current_sum);
53+
}
54+
};

0 commit comments

Comments
 (0)