-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathleetcode_0112_Path_Sum.java
More file actions
52 lines (51 loc) · 1.49 KB
/
leetcode_0112_Path_Sum.java
File metadata and controls
52 lines (51 loc) · 1.49 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
// AC:
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return solve(root, new LinkedList<>(), targetSum);
}
private boolean solve(TreeNode root, List<Integer> curPath, int target) {
if (root == null) {
return false;
}
curPath.add(root.val);
List<Integer> copy = new LinkedList<>(curPath);
// 叶子节点,进行判断
if (root.left == null && root.right == null) {
int tempSum = 0;
for (Integer i: curPath) {
tempSum += i;
}
if (tempSum == target) {
return true;
}
return false;
} else {
boolean checkLeft = solve(root.left, curPath, target);
if (checkLeft) {
return true;
}
// 这里很关键,要重置一次,否则 curPath 在上一步可能已经发生了变化
curPath = copy;
boolean checkRight = solve(root.right, curPath, target);
if (checkRight) {
return true;
}
return false;
}
}
}