Depth-First Search
Path Sum II
DESCRIPTION (inspired by Leetcode.com)
Given the root of a binary tree and an integer target, write a recursive function to find all root-to-leaf paths where the sum of all the values along the path sum to target.
Example 1:
Input:
[1,2,4,4,7,5,1] target = 10
Output:
[[1,2,7],[1,4,5]] # [[1,4,5],[1,2,7]] is also accepted.
The paths are 1 -> 2 -> 7 and 1 -> 4 -> 5
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// TreeNode() {}
// TreeNode(int val) { this.val = val; }
// TreeNode(int val, TreeNode left, TreeNode right) {
// this.val = val;
// this.left = left;
// this.right = right;Run your code to see results here
Have suggestions or found something wrong?
Explanation
This problem is an extension of the Path Sum problem. In this problem, we are asked to return a list of all root-to-leaf paths where the sum of the nodes in the path equals a given target sum.
This is an example of a question which benefits from using a global variable that all recursive calls have access to store the list of all root-to-leaf paths that match the target sum.
Return Values In this case question, we don't need our recursive calls to return any values. Instead, we use depth-first search to traverse each root-to-leaf path in the tree, while maintaining the state of the current path via parameters to the recursive call.
Base Case We can stop recursing when our tree is empty.
Extra Work At each node, we need to add the value of the node to the current path.
Whenever we are at a leaf node, we can check if the value of the current node matches the target. If it does, we can add the current path to the global list of paths.
Helper Function Parent nodes need to pass two pieces of information down to their children:
- The remaining target sum
- The values along the current path (starting from the root).
These values must be passed down as parameters of the recursive call, so we need to introduce a helper function to help us recurse.
Global Variables We will use a global variable to store the root-to-leaf paths that match the given target. This allows us to avoid having to return path arrays up the recursion stack and simplifies collecting all valid paths.
private void dfs(TreeNode node, int target, List<Integer> path, List<List<Integer>> result) {// base caseif (node == null) {return;}// append current value to the pathpath.add(node.val);if (node.left == null && node.right == null) {if (node.val == target) {result.add(new ArrayList<>(path));}}dfs(node.left, target - node.val, path, result);dfs(node.right, target - node.val, path, result);// when our code reaches here, are done exploring all// the root-to-leaf paths that go through the current node.// pop the current value from the path to prepare for the next pathpath.remove(path.size() - 1);}
Global Variables We can use a single global variable that all recursive calls have access to store the list of paths that add up to the target sum.
Solution
public class Solution {public int[][] pathSum(TreeNode root, int target) {List<List<Integer>> result = new ArrayList<>();List<Integer> path = new ArrayList<>();dfs(root, target, path, result);return result.stream().map(l -> l.stream().mapToInt(Integer::intValue).toArray()).toArray(int[][]::new);}private void dfs(TreeNode node, int target, List<Integer> path, List<List<Integer>> result) {// base caseif (node == null) {return;}// append current value to the pathpath.add(node.val);if (node.left == null && node.right == null) {if (node.val == target) {result.add(new ArrayList<>(path));}}dfs(node.left, target - node.val, path, result);dfs(node.right, target - node.val, path, result);// when our code reaches here, are done exploring all// the root-to-leaf paths that go through the current node.// pop the current value from the path to prepare for the next pathpath.remove(path.size() - 1);}}
Animated Solution
public List<List<Integer>> pathSum(TreeNode root, int target) {List<List<Integer>> result = new ArrayList<>();dfs(root, target, new ArrayList<>(), result);return result;}private void dfs(TreeNode node, int target, List<Integer> path, List<List<Integer>> result) {if (node == null) {return;}path.add(node.val);if (node.left == null && node.right == null) {if (node.val == target) {result.add(new ArrayList<>(path));}}dfs(node.left, target - node.val, path, result);dfs(node.right, target - node.val, path, result);path.remove(path.size() - 1);}
path sum II
0 / 41
What is the time complexity of this solution?
O(1)
O(n²)
O(n * logn)
O(n)