/
437. Path Sum III 2.cpp
53 lines (43 loc) · 1.14 KB
/
437. Path Sum III 2.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// https://leetcode.com/problems/path-sum-iii/
/**
* 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
{
int numPaths = 0;
public:
int pathSum(TreeNode *root, int sum)
{
if (root == nullptr)
return numPaths;
countPaths(root, sum);
return numPaths;
}
void countPaths(TreeNode *root, int sum)
{
if (root == nullptr)
return;
int currentSum = 0;
DFS(root, currentSum, sum);
countPaths(root->left, sum);
countPaths(root->right, sum);
}
void DFS(TreeNode *root, int currentSum, int sum)
{
if (root == nullptr)
return;
currentSum += root->val;
if (currentSum == sum)
numPaths++;
DFS(root->left, currentSum, sum);
DFS(root->right, currentSum, sum);
}
};