Skip to content

Commit 02ee104

Browse files
committed
Path Sum/ Path Sum II
1 parent d62ab6a commit 02ee104

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

112 Path Sum.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
3+
4+
For example:
5+
Given the below binary tree and sum = 22,
6+
5
7+
/ \
8+
4 8
9+
/ / \
10+
11 13 4
11+
/ \ \
12+
7 2 1
13+
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
14+
'''
15+
16+
# Definition for a binary tree node.
17+
class TreeNode(object):
18+
def __init__(self, x):
19+
self.val = x
20+
self.left = None
21+
self.right = None
22+
23+
24+
class Solution(object):
25+
def hasPathSum(self, root, sum):
26+
"""
27+
:type root: TreeNode
28+
:type sum: int
29+
:rtype: bool
30+
"""
31+
if not root:
32+
return False
33+
sum -= root.val
34+
if sum == 0 and root.left is None and root.right is None:
35+
return True
36+
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
37+
38+
39+
if __name__ == "__main__":
40+
None

113 Path Sum II.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'''
2+
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
3+
4+
For example:
5+
Given the below binary tree and sum = 22,
6+
5
7+
/ \
8+
4 8
9+
/ / \
10+
11 13 4
11+
/ \ / \
12+
7 2 5 1
13+
return
14+
[
15+
[5,4,11,2],
16+
[5,8,4,5]
17+
]
18+
'''
19+
20+
# Definition for a binary tree node.
21+
class TreeNode(object):
22+
def __init__(self, x):
23+
self.val = x
24+
self.left = None
25+
self.right = None
26+
27+
28+
class Solution(object):
29+
def pathSum(self, root, sum):
30+
"""
31+
:type root: TreeNode
32+
:type sum: int
33+
:rtype: List[List[int]]
34+
"""
35+
result = []
36+
self._pathSum(root, sum, [], result)
37+
return result
38+
39+
def _pathSum(self, root, sum, curr, result):
40+
if not root:
41+
return
42+
sum -= root.val
43+
if sum == 0 and root.left is None and root.right is None:
44+
result.append(curr + [root.val])
45+
if root.left:
46+
self._pathSum(root.left, sum, curr + [root.val], result)
47+
if root.right:
48+
self._pathSum(root.right, sum, curr + [root.val], result)
49+
50+
51+
if __name__ == "__main__":
52+
None

0 commit comments

Comments
 (0)