-
Notifications
You must be signed in to change notification settings - Fork 43
/
TwoSumIV.java
120 lines (111 loc) · 3.22 KB
/
TwoSumIV.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package LeetCodeJava.Tree;
// https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
import LeetCodeJava.DataStructure.TreeNode;
import java.util.*;
public class TwoSumIV {
// V0
// public boolean findTarget(TreeNode root, int k) {
//
// if (root == null) {
// return false;
// }
//
// if (root.equals(null)){
// return false;
// }
//
// if (root.left == null && root.right == null) {
// return false;
// }
//
// //HashMap<Integer, Integer> dict = new HashMap<>();
// HashSet<Integer> set = new HashSet<>();
// Queue<TreeNode> queue = new LinkedList<>();
// queue.add(root);
//
// while (!queue.isEmpty()) {
//
// while (!queue.isEmpty()) {
//
// System.out.println("set = " + set.toString());
//
// TreeNode cur = queue.poll();
// if (set.contains(k - cur.val)) {
// return true;
// }
//
// set.add(cur.val);
//
// if (cur.left != null) {
// queue.add(cur.left);
// }
//
// if (cur.right != null) {
// queue.add(cur.right);
// }
// }
// }
//
// return false;
// }
// V1
// IDEA : SET + RECURSIVE
// https://leetcode.com/problems/two-sum-iv-input-is-a-bst/editorial/
public boolean findTarget(TreeNode root, int k) {
Set< Integer > set = new HashSet();
return find(root, k, set);
}
public boolean find(TreeNode root, int k, Set < Integer > set) {
if (root == null)
return false;
if (set.contains(k - root.val))
return true;
set.add(root.val);
return find(root.left, k, set) || find(root.right, k, set);
}
// V2
// IDEA : BFS + HASHSET
// https://leetcode.com/problems/two-sum-iv-input-is-a-bst/editorial/
public boolean findTarget_2(TreeNode root, int k) {
Set < Integer > set = new HashSet();
Queue < TreeNode > queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
if (queue.peek() != null) {
TreeNode node = queue.remove();
if (set.contains(k - node.val))
return true;
set.add(node.val);
queue.add(node.right);
queue.add(node.left);
} else
queue.remove();
}
return false;
}
// V3
// IDEA : BST
// https://leetcode.com/problems/two-sum-iv-input-is-a-bst/editorial/
public boolean findTarget_3(TreeNode root, int k) {
List < Integer > list = new ArrayList();
inorder(root, list);
int l = 0, r = list.size() - 1;
while (l < r) {
int sum = list.get(l) + list.get(r);
if (sum == k)
return true;
if (sum < k)
l++;
else
r--;
}
return false;
}
public void inorder(TreeNode root, List < Integer > list) {
if (root == null)
return;
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}