113. Path Sum II

PHOTO EMBED

Wed Mar 15 2023 12:15:06 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> v;
    void solve(TreeNode* root, vector<int> &ans, int curr, int targetSum)
    {
        if(!root) return;
        curr+=root->val;
        ans.push_back(root->val);
        if(curr==targetSum && !root->left && !root->right) v.push_back(ans);
        if(root->left) solve(root->left, ans, curr, targetSum);
        if(root->right) solve(root->right, ans, curr, targetSum);
        ans.pop_back();
    }
    
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<int> ans;
        solve(root, ans, 0, targetSum);
        return v;
    }
};
content_copyCOPY

https://leetcode.com/problems/path-sum-ii/