-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath-sum-iii.py
39 lines (27 loc) · 985 Bytes
/
path-sum-iii.py
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
#https://leetcode.com/problems/path-sum-iii/submissions/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def DepthFirstSearch(self, root, sum):
ans = 0
if not root:
return ans
else:
if root.val == sum:
ans = 1
ans += self.DepthFirstSearch(root.left, sum - root.val)
ans += self.DepthFirstSearch(root.right, sum - root.val)
return ans
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
ans = 0
if not root:
return ans
else:
ans += self.DepthFirstSearch(root, sum)
ans += self.pathSum(root.left, sum)
ans += self.pathSum(root.right, sum)
return ans