Advertisement
jayati

Path Sum III

May 10th, 2024
485
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  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. class Solution {
  13. public:
  14.     int ans=0;
  15.     int pathSum(TreeNode* root, int targetSum) {
  16.         if(root)
  17.         {
  18.             dfs(root,targetSum);
  19.             pathSum(root->left,targetSum);
  20.             pathSum(root->right,targetSum);
  21.         }
  22.         return ans;
  23.     }
  24.     void dfs(TreeNode* root,long long sum)
  25.     {
  26.         if(!root)
  27.         {
  28.             return;
  29.         }
  30.         if(root->val==sum)
  31.         {
  32.             ans++;
  33.         }
  34.         dfs(root->left,sum-root->val);
  35.         dfs(root->right,sum-root->val);
  36.     }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement