Path Sum II
TreesDFS
Problem Statement
Given the root of a binary tree and an integer `targetSum`, return all root-to-leaf paths where the sum of the node values in the path equals `targetSum`. Each path should be returned as a list of the node values, not node references.
Example
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Solution: Depth-First Search (DFS)
The problem can be solved efficiently using a recursive Depth-First Search. We traverse the tree, keeping track of the current path and the remaining sum.
Algorithm Steps
- Create a recursive function `dfs(node, remainingSum, path, result)`.
- Base Case: If `node` is null, return.
- Add the current node to the `path`.
- If the current node is a leaf and its value equals the `remainingSum`, add the current `path` to the `result`.
- Recursively call `dfs` on the left and right children.
- Backtrack by removing the current node from the `path`.
Paths Found: 0
Visiting node 5. Remaining sum: 17.
Path Sum II Solution