|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * struct TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode *left; |
| 6 | + * TreeNode *right; |
| 7 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 8 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 10 | + * }; |
| 11 | + */ |
| 12 | + |
| 13 | +class Solution { |
| 14 | + public: |
| 15 | + //helper method |
| 16 | + int helper(TreeNode *root,int sum){ |
| 17 | + if(root == nullptr) return 0; |
| 18 | + return (root->val==sum? 1 : 0) + helper(root->left, sum-root->val) + helper(root->right, sum-root->val); |
| 19 | + } |
| 20 | + |
| 21 | + int pathSum(TreeNode* root, int sum) { |
| 22 | + if(root == nullptr) return 0; |
| 23 | + return helper(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); |
| 24 | + } |
| 25 | +}; |
| 26 | + |
| 27 | +# # Definition for a binary tree node. |
| 28 | +# # class TreeNode: |
| 29 | +# # def __init__(self, x): |
| 30 | +# # self.val = x |
| 31 | +# # self.left = None |
| 32 | +# # self.right = None |
| 33 | + |
| 34 | +# class Solution: |
| 35 | +# def pathSum(self, root: TreeNode, sum: int) -> int: |
| 36 | +# if not root: |
| 37 | +# return 0 |
| 38 | +# return self.helper(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) |
| 39 | + |
| 40 | +# def helper(self, root, sum): |
| 41 | +# if not root: |
| 42 | +# return 0 |
| 43 | + |
| 44 | +# return (1 if root.val == sum else 0) + self.helper(root.left, sum - root.val) + self.helper(root.right, sum - root.val) |
0 commit comments