Skip to content

Commit 10b8c6f

Browse files
authored
Merge pull request neetcode-gh#1975 from Mahim1997/dev/112_Java
112. Path Sum
2 parents 4e553ff + ab6da1a commit 10b8c6f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

java/112-Path-Sum.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
private boolean isLeafNode(TreeNode node) {
18+
return ((node.left == null) && (node.right == null));
19+
}
20+
21+
public boolean hasPathSum(TreeNode root, int targetSum) {
22+
// Edge case: No nodes
23+
if(root == null) {
24+
return false;
25+
}
26+
27+
targetSum -= root.val;
28+
if(isLeafNode(root)) {
29+
return (targetSum == 0);
30+
}
31+
return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
32+
}
33+
}

0 commit comments

Comments
 (0)
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