-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_112.java
More file actions
38 lines (31 loc) · 953 Bytes
/
Copy pathP_112.java
File metadata and controls
38 lines (31 loc) · 953 Bytes
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
package leetcode.easy;
import utils.DataStructures.TreeNode;
@SuppressWarnings("ConstantConditions")
public class P_112 {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == sum;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
boolean res;
public boolean hasPathSumInOrder(TreeNode root, int sum) {
dfs(root, sum, new int[] { 0 });
return res;
}
private void dfs(TreeNode node, int sum, int[] path) {
if (node == null) {
return;
}
path[0] += node.val;
dfs(node.left, sum, path);
if (node.left == null && node.right == null) {
res |= path[0] == sum;
}
dfs(node.right, sum, path);
path[0] -= node.val;
}
}