Simple Backtracking Approach


#1

`void func(TreeNode* A, vector& vec, string &s)
{
s+= ‘0’+(A->val);
if (!A->left && !A->right)
{
vec.push_back(s);
s = s.substr(0,s.size()-1);
return;
}
else if(A->left && !A->right)
{
func(A->left, vec, s);
s = s.substr(0,s.size()-1);
}
else if (!A->left && A->right)
{
func(A->right, vec, s);
s = s.substr(0,s.size()-1);
}
else
{
func(A->left, vec, s);
func(A->right, vec, s);
s = s.substr(0,s.size()-1);
}
}
int Solution::sumNumbers(TreeNode* A) {
if (!A) return 0;
vectorvec;
string s = “”;
func(A,vec,s);

int ans = 0;
for (auto x: vec)
{
    int tmp = 0;
    for (auto c:x)
    {
        int v = c-'0';
        tmp = (tmp*10)%1003;
        tmp = (tmp+v)%1003;
    }
    ans = (ans+tmp)%1003;
}
return ans;

}`


#2

Bro can you please explain me how does the final for loop works, actually I did the same way except the last for loop , there I tried using stoll() but it was giving out of range error. I can sense this works but could give any insights.