Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 081a296

Browse files
authored
Create Path_Sum.py
1 parent ebd2842 commit 081a296

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

‎Leetcode_30day_challenge/Path_Sum.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# https://leetcode.com/problems/path-sum/
2+
'''
3+
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
4+
Solution: O(N) Time and O(Height) Space
5+
'''
6+
7+
class Solution:
8+
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
9+
def solve(root, sums):
10+
if root is None:
11+
return False
12+
13+
if root.left is None and root.right is None and root.val == sums:
14+
return True
15+
sums -= root.val
16+
return solve(root.left, sums) or solve(root.right, sums)
17+
18+
19+
res = solve(root, targetSum)
20+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /