Skip to content

Commit e64fd11

Browse files
committed
update 0112 Solution for Java
1 parent 332f430 commit e64fd11

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
110
class Solution {
2-
public boolean hasPathSum(TreeNode root, int sum) {
3-
if (root == null) return false;
4-
sum -= root.val;
5-
return (root.left == null && root.right == null && sum == 0) ||
6-
hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
11+
public static boolean hasPathSum(TreeNode root, int sum) {
12+
if (root == null) {
13+
return false;
14+
}
15+
return hasPathSum(root, 0, sum);
16+
}
17+
18+
public static boolean hasPathSum(TreeNode root, int sum, int target) {
19+
if (root == null) {
20+
return false;
21+
}
22+
if (root.left == null && root.right == null) {
23+
return sum + root.val == target;
24+
}
25+
26+
sum += root.val;
27+
return hasPathSum(root.left, sum, target) || hasPathSum(root.right, sum, target);
728
}
829
}

0 commit comments

Comments
 (0)