-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_112_path_sum.java
More file actions
45 lines (38 loc) · 1.09 KB
/
Copy path_112_path_sum.java
File metadata and controls
45 lines (38 loc) · 1.09 KB
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
45
public class _112_path_sum {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
public boolean check(TreeNode curNode, int curSum, int targetSum) {
if (curNode == null) {
return false;
}
curSum += curNode.val;
if (isLeaf(curNode)) {
return curSum == targetSum;
}
boolean checkLeft = check(curNode.left, curSum, targetSum);
if (checkLeft) {
return true;
}
boolean checkRight = check(curNode.right, curSum, targetSum);
if (checkRight) {
return true;
}
return false;
}
public boolean hasPathSum(TreeNode root, int targetSum) {
return check(root, 0, targetSum);
}
}