forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-sum-iii.cpp
More file actions
30 lines (28 loc) · 732 Bytes
/
path-sum-iii.cpp
File metadata and controls
30 lines (28 loc) · 732 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
// Time: O(n^2)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) {
return 0;
}
return pathSumHelper(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
private:
int pathSumHelper(TreeNode* root, int prev, int sum) {
if (!root) {
return 0;
}
int curr = prev + root->val;
return (curr == sum) + pathSumHelper(root->left, curr, sum) + pathSumHelper(root->right, curr, sum);
}
};