Skip to content

Commit e4c1d92

Browse files
authored
Update 0112-path-sum.java
#2510
1 parent 127c9c3 commit e4c1d92

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

Diff for: java/0112-path-sum.java

+11-14
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,17 @@
1414
* }
1515
*/
1616
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-
}
17+
//This would be easily solved by DFS and then comparing the values
18+
public boolean dfs(TreeNode root, int targetSum, int currSum){
19+
if(root == null) return false;
2620

27-
targetSum -= root.val;
28-
if(isLeafNode(root)) {
29-
return (targetSum == 0);
21+
currSum += root.val;
22+
if(root.left == null && root.right == null){
23+
return (currSum == targetSum);
3024
}
31-
return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
25+
return dfs(root.left, targetSum, currSum) || dfs(root.right, targetSum, currSum);
26+
}
27+
public boolean hasPathSum(TreeNode root, int targetSum) {
28+
return dfs(root, targetSum, 0);
3229
}
33-
}
30+
}

0 commit comments

Comments
 (0)