Skip to content

Commit ab6da1a

Browse files
committed
112. Path Sum
1 parent bbc1e33 commit ab6da1a

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)