/**
- Definition for binary tree
- struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- };
/
#define ll long long
vector v;
vector<vector> ans;
void rec(TreeNode A)
{
if(!A)
return;
v.push_back(A->val);
if(!A->right&&!A->left)
ans.push_back(v);
rec(A->left);
rec(A->right);
v.pop_back();
}
ll vi(vector x)
{
reverse(x.begin(), x.end());
ll decimal = 1;
ll total = 0;
for (auto& it : x)
{
total += (it * decimal)%1003;
decimal = 10;
}
return total;
}
int Solution::sumNumbers(TreeNode A) {
ans.clear();
v.clear();
rec(A);
ll sum=0;
for(int i=0;i<ans.size();i++)
{
sum+=vi(ans[i])%1003;
}
return sum%1003;
}
indent preformatted text by 4 spaces
Please find the mistake in this code
sam-aggarwal
#1
Write code properly describing what you have done in each step. otherwise cant help.
Or you can check this beautifully written code in java by me. Like share and Subscribe.
public class Solution {
void Helper(TreeNode A, ArrayList<Integer> sum_string, int sum)
{
if(A==null)
{
return;
}
if(A.left==null && A.right==null)
{
sum=((sum*10)%1003+A.val)%1003;
sum_string.add(sum);
return;
}
sum=((sum*10)%1003+A.val)%1003;
Helper(A.left,sum_string,sum);
Helper(A.right,sum_string,sum);
sum=sum/10;
}
public int sumNumbers(TreeNode A) {
ArrayList<Integer> sum_string=new ArrayList<>();
int path=0;
Helper(A,sum_string,path);
int sum=0;
for(int elem:sum_string)
{
sum=((sum%1003)+(elem%1003))%1003;
}
return sum%1003;
}
}