Path sum
DFS, simple question: only check when we are at a leaf node (somehow my solution was top 99% in terms of both time and space complexity)
from typing import Optional
# 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:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
return self.dfs(root, currSum=0, targetSum=targetSum)
def dfs(self, root, currSum, targetSum) -> bool:
if not root:
return False
if not root.left and not root.right:
if root.val + currSum == targetSum:
return True
else:
currSum = root.val + currSum
return self.dfs(root.left, currSum, targetSum) or self.dfs(root.right, currSum, targetSum)