forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
437_Path_Sum_iii
58 lines (49 loc) · 1.59 KB
/
437_Path_Sum_iii
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
54
55
56
57
58
Leetcode 437: Path Sum III
Detailed video explanation: https://youtu.be/Vam9gldRapY
============================================
C++:
----
class Solution {
int pathSum_a(TreeNode* root, int sum){
if(root == nullptr) return 0;
int res = 0;
if(root->val == sum) res++;
res += pathSum_a(root->left, sum-root->val);
res += pathSum_a(root->right, sum-root->val);
return res;
}
public:
int pathSum(TreeNode* root, int sum) {
if(root == nullptr) return 0;
return pathSum(root->left, sum) + pathSum_a(root, sum) + pathSum(root->right, sum);
}
};
Java:
----
class Solution {
private int pathSum_a(TreeNode root, int sum){
if(root == null) return 0;
int res = 0;
if(root.val == sum) res++;
res += pathSum_a(root.left, sum-root.val);
res += pathSum_a(root.right, sum-root.val);
return res;
}
public int pathSum(TreeNode root, int sum) {
if(root == null) return 0;
return pathSum(root.left, sum) + pathSum_a(root, sum) + pathSum(root.right, sum);
}
}
Python3:
-------
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
def pathSum_a(root, sum):
if root == None: return 0
res = 0
if root.val == sum: res += 1
res += pathSum_a(root.left, sum-root.val);
res += pathSum_a(root.right, sum-root.val);
return res
if root == None: return 0
return self.pathSum(root.left, sum) + pathSum_a(root, sum) + self.pathSum(root.right, sum)