From 6f7bdf6df4faceecf3afc5633feb6abed5060b2f Mon Sep 17 00:00:00 2001 From: Sri Harsha Damarla Date: Fri, 19 Jun 2026 16:02:01 +0530 Subject: [PATCH] path sum implementations --- input.txt | 2 +- src/com/dsa/trees/DepthFirstTraversal.java | 37 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/input.txt b/input.txt index 69ad60e..f874934 100644 --- a/input.txt +++ b/input.txt @@ -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 \ No newline at end of file diff --git a/src/com/dsa/trees/DepthFirstTraversal.java b/src/com/dsa/trees/DepthFirstTraversal.java index 3dfd6ec..a4b9a78 100644 --- a/src/com/dsa/trees/DepthFirstTraversal.java +++ b/src/com/dsa/trees/DepthFirstTraversal.java @@ -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> allPaths = pathSum(root, targetSum); + for (List 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 pathTracer = new LinkedList<>(); + private static List> allPaths = new LinkedList<>(); + public static List> 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; + } }