path sum implementations
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
5,4,8,11,null,13,4,7,2,null,null,null,1
|
||||
5,4,8,11,null,13,4,7,2,null,null,5,1
|
||||
22
|
||||
@@ -4,6 +4,7 @@ import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
|
||||
@@ -32,6 +33,10 @@ public class DepthFirstTraversal {
|
||||
System.out.println("MinDepth: " + minDepth(root));
|
||||
System.out.println("isBalanced: " + isBalanced(root));
|
||||
System.out.println("PathSum Target: " + targetSum + " isPresent: " + hasPathSum(root, targetSum));
|
||||
List<List<Integer>> allPaths = pathSum(root, targetSum);
|
||||
for (List<Integer> path : allPaths) {
|
||||
System.out.println(path);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -84,4 +89,36 @@ public class DepthFirstTraversal {
|
||||
if (hasPathSumLeft) return true;
|
||||
return hasPathSum(root.right, requiredNewSum);
|
||||
}
|
||||
|
||||
private static List<Integer> pathTracer = new LinkedList<>();
|
||||
private static List<List<Integer>> allPaths = new LinkedList<>();
|
||||
public static List<List<Integer>> pathSum(TreeNode root, int targetSum) {
|
||||
if (root == null) return allPaths;
|
||||
pathTracer.add(root.val);
|
||||
if (root.left == null && root.right == null && root.val == targetSum) {
|
||||
allPaths.add(new LinkedList<>(pathTracer));
|
||||
}
|
||||
int requiredNewSum = targetSum - root.val;
|
||||
pathSum(root.left, requiredNewSum);
|
||||
pathSum(root.right, requiredNewSum);
|
||||
pathTracer.removeLast();
|
||||
return allPaths;
|
||||
}
|
||||
|
||||
private static int maxSum;
|
||||
public static int maxPathSum(TreeNode root) {
|
||||
if (root != null) maxSum = root.val;
|
||||
int maxSumInternal = maxPathSumInternal(root);
|
||||
return Math.max(maxSumInternal, maxSum);
|
||||
}
|
||||
|
||||
private static int maxPathSumInternal(TreeNode root) {
|
||||
if (root == null) return 0;
|
||||
int leftMaxSum = maxPathSumInternal(root.left);
|
||||
int rightMaxSum = maxPathSumInternal(root.right);
|
||||
maxSum = Math.max(leftMaxSum + rightMaxSum + root.val, maxSum); //is max including current node in path
|
||||
int pathMax = Math.max(leftMaxSum + root.val, Math.max(rightMaxSum + root.val, root.val)); //for moving up just return one of max sum to parent
|
||||
maxSum = Math.max(pathMax, maxSum);
|
||||
return pathMax;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user