Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112. Path Sum
  • Loading branch information
Mahim1997 committed Jan 9, 2023
commit ab6da1ab0a483d89d9fdbff58b6470ad82c8962e
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);
}
}