Path Sum
LeetCode 112 · Easy · solution, intuition & step-by-step walkthrough
Reduce the target; check at leaves.
This is how I solved Path Sum (LeetCode 112), an easy problem from the Root-to-Leaf Paths pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Subtract each node's value from the target on the way down. At a leaf, the path works exactly when what's left is zero.
Approach
- 1
None → False.
- 2
targetSum −= node.val.
- 3
Leaf → targetSum == 0.
- 4
Otherwise try left or right.
How I solved it
DFS with remaining sumPythonO(n) time · O(h) space
# 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:
if root==None:
return False
#reduce target sum
targetSum = targetSum-root.val
if root.left==None and root.right==None:
return targetSum==0
return self.hasPathSum(root.left,targetSum) or self.hasPathSum(root.right,targetSum)Path Sum — FAQ
What is the intuition behind Path Sum?
Subtract each node's value from the target on the way down. At a leaf, the path works exactly when what's left is zero.
How do you solve Path Sum (LeetCode 112)?
1. None → False. 2. targetSum −= node.val. 3. Leaf → targetSum == 0. 4. Otherwise try left or right.
What is the time and space complexity of Path Sum?
Time: O(n). Space: O(h). (Accepted approach: DFS with remaining sum.)
What are common mistakes in Path Sum?
Only leaf-to-root paths count — an internal node hitting zero isn't enough.