forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_112.java
37 lines (33 loc) · 1.12 KB
/
_112.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _112 {
public static class Solution1 {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.val == sum && root.left == null && root.right == null) {
return true;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
public static class Solution2 {
/**
* My completely original solution on 9/23/2021.
*/
public boolean hasPathSum(TreeNode root, int targetSum) {
return dfs(root, 0, targetSum);
}
private boolean dfs(TreeNode root, int sum, int targetSum) {
if (root == null) {
return false;
}
sum += root.val;
if (root.left == null && root.right == null) {
return sum == targetSum;
}
return dfs(root.left, sum, targetSum) || dfs(root.right, sum, targetSum);
}
}
}