A recursive solution (accepted)


  • 7
    A

    This is a recursive solution, we can change it to iterative easily:

    class Solution {
    public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
    vector<vector<int>> res;
    vector<int> path;

        findAllPath (root, sum, path, res);
        return res;
    }
    

    private:
    void findAllPath (TreeNode *root, int sum, vector<int> &path, vector<vector<int>> &res)
    {
    if (!root) return;

        path.push_back (root->val);
        if (!root->left && !root->right && root->val == sum)
            res.push_back (path);
        if (root->left)
            findAllPath (root->left, sum - root->val, path, res);
        if (root->right)
            findAllPath (root->right, sum - root->val, path, res);
        path.pop_back ();
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.