-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTSIterator.java
More file actions
47 lines (34 loc) · 942 Bytes
/
Copy pathBTSIterator.java
File metadata and controls
47 lines (34 loc) · 942 Bytes
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
import java.util.Iterator;
import java.util.Stack;
public class BTSIterator implements Iterator<Integer> {
Tree tree;
Stack<Node> stack;
// using stack to get all the nodes in the tree
BTSIterator(Tree tree) {
stack = new Stack<>();
this.tree = tree;
Node node = tree.root;
update(node); // updating stack
}
// implementing interface
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public Integer next() {
Node remove = stack.pop();
update(remove.right); // before return node, first update stack further
return remove.value;
}
public void update(Node node){
while(node != null){
stack.add(node);
node = node.left;
}
}
// making a concrete Interator
public Iterator<Integer> getIterator() {
return new BTSIterator(tree);
}
}