forked from mickey0524/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112.Path-Sum.java
44 lines (40 loc) · 1.05 KB
/
112.Path-Sum.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
38
39
40
41
42
43
44
// https://leetcode.com/problems/path-sum/
//
// algorithms
// Easy (37.95%)
// Total Accepted: 320,318
// Total Submissions: 844,145x
// beats 100.0% of java submissions
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return recursive(root, 0, sum);
}
public boolean recursive(TreeNode root, int curSum, int sum) {
if (root.left == null && root.right == null) {
if (curSum + root.val == sum) {
return true;
}
return false;
}
boolean res = false;
if (root.left != null) {
res = recursive(root.left, curSum + root.val, sum);
}
if (!res && root.right != null) {
res = recursive(root.right, curSum + root.val, sum);
}
return res;
}
}