Beautiful solution without any global variable ( C++ )


#1

void rootleaf( TreeNode *pvar, int sum, vector<vector> &ans, vector curr ){

if( pvar != NULL ){
    
    curr.push_back( pvar->val );
    
    rootleaf( pvar->left, sum - pvar->val, ans, curr );
    rootleaf( pvar->right, sum - pvar->val, ans, curr );
    
    if( pvar->left == NULL && pvar->right == NULL && ( (sum - pvar->val ) == 0 ) )
        ans.push_back( curr );
}

}

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

vector< vector<int> > ans;
vector<int> curr;

rootleaf( A, B, ans, curr );

return ans;

}