My recursive solution in C++


  • 0
    L

    class Solution {
    public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
    vector<int> vec;
    solve(root, sum, vec);
    return v;
    }

    void solve(TreeNode* root, int sum, vector<int>& vec) {
        if (!root) {
            return;
        }
        
        if (root->val != sum) {
            vec.push_back(root->val);
        }else if (root->val == sum) {
            vec.push_back(root->val);
            if (!root->left && !root->right) {
                v.push_back(vec);
            }
        }
        solve(root->left, sum - root->val, vec);
        solve(root->right, sum - root->val, vec);
        vec.pop_back();
    }
    

    private:
    vector<vector<int>> v;
    };


Log in to reply
 

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