Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.2 kB
4
Indexable
Never
/**
 * 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:
    int pathSum(TreeNode* root, int targetSum) {
        return rec(root, targetSum, false);
    }

    int rec(TreeNode* root, long long targetSum, bool includeRoot) {
        if (root==NULL) {
            return 0;
        }
        // cout << " | " << root->val << " " << targetSum << " " << includeRoot;
            
        int result = 0;
        if (root->val==targetSum) {
            result++;
        }
        result = result + rec(root->left, targetSum-root->val, true) + rec(root->right, targetSum-root->val, true);
        
        if (includeRoot) {
            // cout << " " << result << endl;
            return result;
        }
        result = result + rec(root->left, targetSum, false) + rec(root->right, targetSum, false);
        // cout << " " << result << endl;
        return result;
    }
};
Leave a Comment