Path Sum II


class Solution {
public:
    void helper(TreeNode *root, int sum, vector<int>& tmp, vector<vector<int> >& res)
    {        
        if (! root) return;
        
        sum = sum - root->val;
        tmp.push_back(root->val);
        
        if (sum == 0 && root->left == NULL && root->right == NULL) res.push_back(tmp);
        
        helper(root->left,  sum, tmp, res);
        helper(root->right, sum, tmp, res);
        
        tmp.pop_back();
        sum = sum + root->val;
    }
    
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int> > res;
        vector<int> tmp;
        
        helper(root, sum, tmp, res);
        
        return res;
    }
    
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s