Skip to content

Commit

Permalink
112. Path Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahim1997 committed Jan 9, 2023
1 parent bbc1e33 commit ab6da1a
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions java/112-Path-Sum.java
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);
}
}

0 comments on commit ab6da1a

Please sign in to comment.