-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIterator.java
More file actions
78 lines (61 loc) · 1.81 KB
/
Iterator.java
File metadata and controls
78 lines (61 loc) · 1.81 KB
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
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
class Node<T> {
public T value;
public Node<T> left, right, parent;
public Node(T value) {
this.value = value;
}
public Node(T value, Node<T> left, Node<T> right) {
this.value = value;
this.left = left;
this.right = right;
left.parent = right.parent = this;
}
public Iterator<Node<T>> preOrder() {
return new PreorderIterator<>(this);
}
@Override
public String toString() {
return value.toString();
}
}
class PreorderIterator<T> implements Iterator<Node<T>> {
// https://codereview.stackexchange.com/questions/41844/iterator-for-binary-tree-pre-in-and-post-order-iterators
private final Deque<Node<T>> stack;
public PreorderIterator(Node<T> root) {
stack = new ArrayDeque<>();
stack.add(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public Node<T> next() {
if (!hasNext()) {
throw new NoSuchElementException("No more nodes remain to iterate");
}
final Node<T> node = stack.pop();
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
return node;
}
}
class DemoIterator {
public static void main(String[] args) {
Node<Integer> n1 = new Node<>(1);
Node<Integer> n2 = new Node<>(2);
Node<Integer> n3 = new Node<>(3, n1, n2);
Iterator<Node<Integer>> it = n3.preOrder();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}