-
Notifications
You must be signed in to change notification settings - Fork 1
/
InOrderIterator.java
45 lines (38 loc) · 992 Bytes
/
InOrderIterator.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
import java.util.Deque;
import java.util.LinkedList;
public class InOrderIterator implements TreeIterator {
private Deque<TreeNode> stack;
private TreeNode cur;
public InOrderIterator(TreeNode root) {
this.stack = new LinkedList<>();
cur = root;
while(cur != null) {
stack.addFirst(cur);
cur = cur.left;
}
}
@Override
public boolean hasNext() {
return stack.size() != 0;
}
@Override
public Object next() {
if(stack.isEmpty()) {
return null;
}
else {
Object ret = null;
do {
if (cur != null) {
stack.addFirst(cur);
cur = cur.left;
} else {
cur = stack.removeFirst();
ret = cur.key;
cur = cur.right;
}
} while (cur != null);
return ret;
}
}
}