Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22trueroot = [1,2,3], targetSum = 5false
Passing rem = target − node.val converts the path-sum check into a single equality at the leaf: rem == 0. The || operator short-circuits — once any valid path is found the recursion unwinds immediately without exploring further nodes.
You could list every root to leaf path and sum each one. But we can carry the remaining amount down the tree instead, and never store a path.
Subtract the node value from the target as you go down. At a leaf, check whether the remaining amount is exactly 0. If either subtree returns true, the answer is true. The check must happen only at leaves, because a path has to end at a leaf.
Pass the remaining target down, and check it only at leaves. The or operator stops the search as soon as one path works.
Run the animation above on your own input, or watch the 1:43 video explanation of Path Sum with a dry run and Java code.