Please correct me if I am wrong but isn’t my algorithm O(N) (where N is # of nodes in the given tree).
Following is my algorithm, the only difference from solution (provided in the tutorial) is I am updating ArrayList current path (‘cpath’ in my code) only when I find a path.
public static List<List> findPaths(TreeNode root, int sum) {
List<List> allpaths = new ArrayList<List>();
List cpath = new ArrayList();
dfs(root, sum, cpath, allpaths);
return allpaths;
}
private static void dfs(TreeNode root, int sum, List cpath, List<List> allpaths){
if(root == null){
return;
}
if(root.val == sum && root.left == null && root.right == null){
cpath.add(root.val);
allpaths.add(cpath);
}
List temp = new ArrayList();
temp.addAll(cpath);
temp.add(root.val);
dfs(root.left, sum-root.val, temp, allpaths);
dfs(root.right, sum-root.val, temp, allpaths);
}