129 Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> helper(TreeNode* root) {
vector<string> res;
if ( root == NULL ) return res;
if ( root->left == NULL and root->right == NULL) { res.push_back(to_string(root->val)); return res;}
vector<string> left = helper(root->left);
vector<string> right = helper(root->right);
int l = left.size(), r = right.size();
for ( int i = 0; i <= l-1; i++ ) {
string s = to_string(root->val) + left[i];
res.push_back(s);
}
for ( int i = 0; i <= r-1; i++ ) {
string s = to_string(root->val) + right[i];
res.push_back(s);
}
return res;
}
int sumNumbers(TreeNode* root) {
vector<string> res = helper(root);
int sum = 0, n = res.size();
for ( int i = 0; i<= n-1; i++ ) sum += atoi(res[i].c_str());
return sum;
}
};
Notes
DETAILS
distinguish a leaf node! For example:
1 / \ 2 3 \ 4
The result is 124 + 13 = 137. (12 cannot be counted as a number here.)
Note the appearance of zero! For example:
1 / \ 2 3 \ 0
If only record an integer in the array, 120 may be mis-represented as 12. So note the trick to record a vector of strings!