path sum
This commit is contained in:
@@ -1 +1,2 @@
|
||||
1,2,2,3,3,null,null,4,4
|
||||
5,4,8,11,null,13,4,7,2,null,null,null,1
|
||||
22
|
||||
@@ -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<TreeNode> 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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user