Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/21733805f784f83731162f6fcc8fbb95 to your computer and use it in GitHub Desktop.
Save InterviewBytes/21733805f784f83731162f6fcc8fbb95 to your computer and use it in GitHub Desktop.
Path Sum II
package com.interviewbytes.trees;
import java.util.ArrayList;
import java.util.List;
public class PathSum2 {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> paths = new ArrayList<>();
helper(root, sum, paths, new ArrayList<Integer>());
return paths;
}
private void helper(TreeNode node, int sum, List<List<Integer>> paths, List<Integer> path) {
if (node == null) return;
path.add(node.val);
if (node.left == null && node.right == null && node.val == sum) {
paths.add(new ArrayList<>(path));
}
helper(node.left, sum - node.val, paths, path);
helper(node.right, sum - node.val, paths, path);
path.remove(path.size() - 1);
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment