From ab6da1ab0a483d89d9fdbff58b6470ad82c8962e Mon Sep 17 00:00:00 2001 From: Mahim Mahbub Date: Tue, 10 Jan 2023 00:27:54 +0600 Subject: [PATCH] 112. Path Sum --- java/112-Path-Sum.java | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 java/112-Path-Sum.java diff --git a/java/112-Path-Sum.java b/java/112-Path-Sum.java new file mode 100644 index 000000000..887e65531 --- /dev/null +++ b/java/112-Path-Sum.java @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private boolean isLeafNode(TreeNode node) { + return ((node.left == null) && (node.right == null)); + } + + public boolean hasPathSum(TreeNode root, int targetSum) { + // Edge case: No nodes + if(root == null) { + return false; + } + + targetSum -= root.val; + if(isLeafNode(root)) { + return (targetSum == 0); + } + return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum); + } +} \ No newline at end of file