-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC8.CPP
More file actions
31 lines (28 loc) · 955 Bytes
/
LC8.CPP
File metadata and controls
31 lines (28 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Problem link : https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3417/
#include <bits/stdc++.h>
using namespace std;
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 dfs(TreeNode* root, int sum)
{
if (!root)
{
return 0;
}
int ans = root->val==sum ? 1 : 0;
return (ans+dfs(root->left, sum-(root->val))+dfs(root->right, sum-(root->val)));
}
int pathSum(TreeNode* root, int sum) {
if (!root)
return 0;
return (dfs(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum));
}
};