-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112_Path_Sum.py
More file actions
47 lines (37 loc) · 1.37 KB
/
112_Path_Sum.py
File metadata and controls
47 lines (37 loc) · 1.37 KB
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
# 4 Possible Solutions
# 1. Recursion
# 2. Iteration
# 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:
# Recursive
# Time: O(N), Space: O(N)
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node, currentSum):
if not node:
return False
currentSum += node.val
if not node.left and not node.right:
return currentSum == targetSum
return (dfs(node.left, currentSum) or dfs(node.right, currentSum))
return dfs(root, 0)
# Iterative
# Time: O(N), Space:(N)
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
currentSum = 0
stack = [(root,currentSum + root.val)]
while stack:
node, currentSum = stack.pop()
if not node.left and not node.right and targetSum == currentSum:
return True
if node.left:
stack.append((node.left, currentSum + node.left.val))
if node.right:
stack.append((node.right, currentSum + node.right.val))
return False