forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_653.java
57 lines (49 loc) · 1.52 KB
/
_653.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
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _653 {
public static class Solution1 {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
List<Integer> list = new ArrayList<>();
dfs(root, list);
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i) + list.get(j) == k) {
return true;
}
}
}
return false;
}
private void dfs(TreeNode root, List<Integer> list) {
list.add(root.val);
if (root.left != null) {
dfs(root.left, list);
}
if (root.right != null) {
dfs(root.right, list);
}
}
}
public static class Solution2 {
public boolean findTarget(TreeNode root, int k) {
return dfs(root, new HashSet(), k);
}
private boolean dfs(TreeNode root, Set<Integer> set, int k) {
if (root == null) {
return false;
}
if (set.contains(k - root.val)) {
return true;
}
set.add(root.val);
return dfs(root.left, set, k) || dfs(root.right, set, k);
}
}
}