Simple solution to problem in c++


#1
void Sum(TreeNode* a, int b,vector<int>v, vector<vector<int>>&ans){
if(a==NULL )
return ;
if(b-(a->val)==0 && a->left==NULL && a->right==NULL){
    v.push_back(a->val);    
    ans.push_back(v);
    return ;
}
v.push_back(a->val);
Sum(a->left,b-(a->val),v,ans);
Sum(a->right,b-(a->val),v,ans);

}

vector<vector > Solution::pathSum(TreeNode* a, int b) {
vectorv;
vector<vector>ans;
Sum(a,b,v,ans);
return ans;
}


#2

same code show memory problem
void Sum(TreeNode* a, int b,vectorv, vector<vector>&ans){
if(a==NULL )
return ;
if(b-(a->val)==0 && a->left==NULL && a->right==NULL){
v.push_back(a->val);
ans.push_back(v);
return ;
}
v.push_back(a->val);
Sum(a->left,b-(a->val),v,ans);
Sum(a->right,b-(a->val),v,ans);
}

vector<vector > Solution::pathSum(TreeNode* a, int b) {
vector v;
vector<vector >ans;
Sum(a,b,v,ans);
return ans;
}


#3

Don’t copy vector v each time in the recursion call. Instead, pass it as a reference and push-pop accordingly. For reference please see the code below:-

void path_sum(TreeNode * A, int sum, int B, vector<int> &path_elements, vector<vector<int> > &soln){
 
if(A==NULL)
    return;
 
else if(sum+A->val==B && A->left==NULL && A->right==NULL){
    path_elements.push_back(A->val);
    soln.push_back(path_elements);
    path_elements.pop_back();
}
    
else if(sum+A->val!=B && A->left==NULL && A->right==NULL) 
    return;

else{
    path_elements.push_back(A->val);
    path_sum(A->left,sum+A->val,B,path_elements,soln);
    path_sum(A->right,sum+A->val,B,path_elements,soln);
    path_elements.pop_back();
}

}

vector<vector > Solution::pathSum(TreeNode* A, int B) {

TreeNode * root=A;
vector<vector<int> > soln;
vector<int> path_elements;
path_sum(A,0,B,path_elements,soln);
return soln;

}


#4

Thanks, your solution help me…