My C++ Solution (13ms)


  • 0
    W
    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> allPaths;
            vector<int> path;
            helper(root, allPaths, path, sum);
            return allPaths;
        }
        void helper(TreeNode* root, vector<vector<int>>& allPaths, vector<int>& path, int sum){
            if(!root) return;
            if(!(root->left)&&!(root->right)&&sum==root->val){
                path.push_back(root->val);
                allPaths.push_back(path);
                path.pop_back();
                return;
            }
            path.push_back(root->val);
            helper(root->left, allPaths, path, sum-root->val);
            helper(root->right, allPaths, path, sum-root->val);
            path.pop_back();
        }
    };
    

Log in to reply
 

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