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 pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy