Skip to content

Commit 9ff09b3

Browse files
refactor 112
1 parent 72c44f2 commit 9ff09b3

File tree

1 file changed

+20
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-0
lines changed

src/main/java/com/fishercoder/solutions/_112.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,24 @@ public boolean hasPathSum(TreeNode root, int sum) {
1414
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
1515
}
1616
}
17+
18+
public static class Solution2 {
19+
/**
20+
* My completely original solution on 9/23/2021.
21+
*/
22+
public boolean hasPathSum(TreeNode root, int targetSum) {
23+
return dfs(root, 0, targetSum);
24+
}
25+
26+
private boolean dfs(TreeNode root, int sum, int targetSum) {
27+
if (root == null) {
28+
return false;
29+
}
30+
sum += root.val;
31+
if (root.left == null && root.right == null) {
32+
return sum == targetSum;
33+
}
34+
return dfs(root.left, sum, targetSum) || dfs(root.right, sum, targetSum);
35+
}
36+
}
1737
}

0 commit comments

Comments
 (0)