113. Path Sum II - cocoder39/coco39_LC GitHub Wiki

113. Path Sum II

dfs + backtracking, O(n) time and O(height) space for call stack

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if(! root) {
            return res;
        }
        vector<int> path;
        helper(res, path, root, sum);
        return res;
    }
private:
    void helper(vector<vector<int>>& res, vector<int>& path, TreeNode* root, int sum){
        path.push_back(root->val);
        if (! root->left && ! root->right && root->val == sum) {
            res.push_back(path);
        }
        if (root->left) {
            helper(res, path, root->left, sum-root->val);
        }
        if (root->right) {
            helper(res, path, root->right, sum-root->val);
        }
        path.pop_back();
    }
};
⚠️ **GitHub.com Fallback** ⚠️