Question:
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
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
.
Answer:
class Solution {
public:
int sumNumbers(TreeNode *root) {
vector<vector<int>> res;
vector<int> a;
path(root,a,res);
int sum=0;
int len=res.size();
for(int i=0;i<len;i++){
sum+=StrToInt(res[i]);
}
return sum;
}
void path(TreeNode *root,vector<int> &a,vector<vector<int>> &res){
if(!root)return;
else{
a.push_back(root->val);
if(root->left){
path(root->left,a,res);
}
if(root->right){
path(root->right,a,res);
}
if(!root->left&&!root->right&&root){
vector<int> b=a;
res.push_back(b);
}
a.pop_back();
return;
}
}
int StrToInt(vector<int> s) {
int len=s.size();
int res=0;
for(int i=0;i<len;++i){
int j=len-i-1;
int num=s[i];
while(j>0){
num=num*10;
--j;
}
res+=num;
}
return res;
}
};
No comments:
Post a Comment