112. Path Sum
Problem
Decide whether the binary tree has a root-to-leaf path whose node values add up to targetSum.
Example: [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 → true (5 → 4 → 11 → 2)
Subtract node values on the way down; at a leaf, check the remainder equals the leaf value.
Complexity: O(n).
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return root.val == targetSum
rest = targetSum - root.val
return self.hasPathSum(root.left, rest) or self.hasPathSum(root.right, rest)
t = make_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1])
assert Solution().hasPathSum(t, 22) is True
assert Solution().hasPathSum(make_tree([1, 2, 3]), 5) is False
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == targetSum;
int rest = targetSum - root.val;
return hasPathSum(root.left, rest) || hasPathSum(root.right, rest);
}
}
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
if root.Left == nil && root.Right == nil {
return root.Val == targetSum
}
rest := targetSum - root.Val
return hasPathSum(root.Left, rest) || hasPathSum(root.Right, rest)
}