Path Sum
EasyTop Interview 150 TreesProblem
You get the root of a binary tree and a number targetSum. Return true if
some path that starts at the root and ends at a leaf has node values adding up to exactly
targetSum. A leaf is a node with no children.
The tree is given in level order, with null for a missing child.
Constraints
- 0 ≤ number of nodes ≤ 5000
- -1000 ≤ Node.val ≤ 1000
- -1000 ≤ targetSum ≤ 1000
Examples: pick one to animate
Solutions
Time: Each node is visited at most once, with constant work per visit.
Space: The recursion is as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.
Instead of adding up the path, subtract each node's value from the target as you walk down. What is left is the amount the rest of the path must supply. At a leaf, the path works exactly when nothing is left. A node with children can never end a path, so keep going. Return true as soon as either side finds a match.