Simple C++ Recursive Solution


  • 0
    M
    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            if (!root) return {};
            if (!root->left && !root->right && root->val == sum) return {{root->val}};
            auto l = pathSum(root->left, sum - root->val), r = pathSum(root->right, sum - root->val);
            l.insert(l.end(), r.begin(), r.end());
            for (int i = 0; i < l.size(); ++i) l[i].insert(l[i].begin(), root->val);
            return l;
        }
    };
    

Log in to reply
 

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