VISUALGO//PROBLEMS
path sum iii · binary tree – dfsmedium
tree
target
·
sum
·
paths
·
ELEMENTS
root
targetSum
Python
def pathSum(root: TreeNode | None, targetSum: int) -> int:
seen = {0: 1} # prefix sums on the current root-to-node path
def dfs(node: TreeNode | None, total: int) -> int:
if node is None:
return 0
total += node.val
count = seen.get(total - targetSum, 0) # paths ending here that add up to targetSum
seen[total] = seen.get(total, 0) + 1
count += dfs(node.left, total) + dfs(node.right, total)
seen[total] -= 1 # leaving this node: it is no longer on the path
return count
return dfs(root, 0)