From 25da8db42258f71f5563dd984b757fffa94b201a Mon Sep 17 00:00:00 2001 From: Sri Harsha Damarla Date: Thu, 18 Jun 2026 23:41:34 +0530 Subject: [PATCH] path sum --- input.txt | 3 ++- src/com/dsa/trees/DepthFirstTraversal.java | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/input.txt b/input.txt index 646ce06..69ad60e 100644 --- a/input.txt +++ b/input.txt @@ -1 +1,2 @@ -1,2,2,3,3,null,null,4,4 \ No newline at end of file +5,4,8,11,null,13,4,7,2,null,null,null,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 183993a..3dfd6ec 100644 --- a/src/com/dsa/trees/DepthFirstTraversal.java +++ b/src/com/dsa/trees/DepthFirstTraversal.java @@ -4,12 +4,14 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; +import java.util.Optional; import java.util.Queue; public class DepthFirstTraversal { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) { String[] elements = reader.readLine().trim().split(","); + int targetSum = Optional.ofNullable(reader.readLine()).map(Integer::parseInt).orElse(0); Queue queue = new LinkedList<>(); TreeNode root = new TreeNode(Integer.parseInt(elements[0])); queue.offer(root); @@ -29,6 +31,7 @@ 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)); } catch (IOException e) { throw new RuntimeException(e); } @@ -72,4 +75,13 @@ public class DepthFirstTraversal { if (weight > 1) return -1; return Math.max(leftHeight, rightHeight) + 1; } + + public static boolean hasPathSum(TreeNode root, int targetSum) { + if(root == null) return false; + if (root.left == null && root.right == null && root.val == targetSum) return true; + int requiredNewSum = targetSum - root.val; + boolean hasPathSumLeft = hasPathSum(root.left, requiredNewSum); + if (hasPathSumLeft) return true; + return hasPathSum(root.right, requiredNewSum); + } }