forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
} | ||
} |