-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSum.java
82 lines (82 loc) · 2.26 KB
/
TwoSum.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
class TwoSum {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
AscIterator ascIterator = new AscIterator(root);
DesIterator desIterator = new DesIterator(root);
while (ascIterator.peek().val < desIterator.peek().val) {
int sum = ascIterator.peek().val + desIterator.peek().val;
if (sum == k) {
return true;
}
if (sum < k) {
ascIterator.next();
} else {
desIterator.next();
}
}
return false;
}
static abstract class MyIterator {
Deque<TreeNode> stack;
MyIterator(TreeNode root) {
this.stack = new ArrayDeque<>();
}
public boolean hasNext() {
return !stack.isEmpty();
}
public TreeNode getCur() {
if (!hasNext()) {
return null;
}
return stack.pop();
}
public abstract TreeNode next();
public TreeNode peek() {
return stack.peek();
}
protected void firstSmallestNode(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.left;
}
}
protected void firstLargestNode(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.right;
}
}
}
static class AscIterator extends MyIterator {
AscIterator(TreeNode root) {
super(root);
firstSmallestNode(root);
}
@Override
public TreeNode next() {
if (!hasNext()) {
return null;
}
TreeNode cur = getCur();
firstSmallestNode(cur.right);
return cur;
}
}
static class DesIterator extends MyIterator {
DesIterator(TreeNode root) {
super(root);
firstLargestNode(root);
}
@Override
public TreeNode next() {
if (!hasNext()) {
return null;
}
TreeNode cur = getCur();
firstLargestNode(cur.left);
return cur;
}
}
}