Skip to content

Commit

Permalink
feature: path sum dfs revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 15, 2023
1 parent d34ff0c commit bc2c96a
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions trees/PathSum.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,17 @@ def has_path_sum_dfs(self, root: Optional[TreeNode], target_sum: int) -> bool:
if not root:
return False

stack = [(root, target_sum - root.val)]
stack = [(root, root.val)]
while stack:
node, curr_sum = stack.pop()
if not node.left and not node.right and curr_sum == 0:
return True

if node.right:
stack.append((node.right, curr_sum - node.right.val))
if not node.left and not node.right and curr_sum == target_sum:
return True

if node.left:
stack.append((node.left, curr_sum - node.left.val))
stack.append((node.left, curr_sum + node.left.val))

if node.right:
stack.append((node.right, curr_sum + node.right.val))

return False

0 comments on commit bc2c96a

Please sign in to comment.