forked from algorithmzuo/algorithm-primary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode03_PathSum.java
More file actions
60 lines (52 loc) · 1.26 KB
/
Code03_PathSum.java
File metadata and controls
60 lines (52 loc) · 1.26 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package class07;
public class Code03_PathSum {
// 测试链接:https://leetcode.com/problems/path-sum
public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public static boolean isSum = false;
public static boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
isSum = false;
process(root, 0, sum);
return isSum;
}
public static void process(TreeNode x, int preSum, int sum) {
if (x.left == null && x.right == null) {
if (x.val + preSum == sum) {
isSum = true;
}
return;
}
// x是非叶节点
preSum += x.val;
if (x.left != null) {
process(x.left, preSum, sum);
}
if (x.right != null) {
process(x.right, preSum, sum);
}
}
// public static boolean hasPathSum(TreeNode root, int sum) {
// if (root == null) {
// return false;
// }
// return process(root, sum);
// }
//
// public static boolean process(TreeNode root, int rest) {
// if (root.left == null && root.right == null) {
// return root.val == rest;
// }
// boolean ans = root.left != null ? process(root.left, rest - root.val) : false;
// ans |= root.right != null ? process(root.right, rest - root.val) : false;
// return ans;
// }
}