Skip to content

Commit 3da9ce5

Browse files
authored
Create Path Sum - Leetcode 112.py
1 parent 093bc8f commit 3da9ce5

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Path Sum - Leetcode 112.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
9+
10+
def has_sum(root, cur_sum):
11+
if not root:
12+
return False
13+
14+
cur_sum += root.val
15+
16+
if not root.left and not root.right:
17+
return cur_sum == targetSum
18+
19+
return has_sum(root.left, cur_sum) or \
20+
has_sum(root.right, cur_sum)
21+
22+
return has_sum(root, 0)
23+
# Time: O(n)
24+
# Space: O(h) or O(n)

0 commit comments

Comments
 (0)