-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDepthFirstTreeIterator.java
47 lines (37 loc) · 1.13 KB
/
DepthFirstTreeIterator.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
package datastructures;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
/*
* See URL: http://en.wikipedia.org/wiki/Depth-first_search
*/
public class DepthFirstTreeIterator implements Iterator<Node> {
private LinkedList<Node> list;
public DepthFirstTreeIterator(HashMap<String, Node> tree, String identifier) {
list = new LinkedList<Node>();
if (tree.containsKey(identifier)) {
this.buildList(tree, identifier);
}
}
private void buildList(HashMap<String, Node> tree, String identifier) {
list.add(tree.get(identifier));
ArrayList<String> children = tree.get(identifier).getChildren();
for (String child : children) {
// Recursive call
this.buildList(tree, child);
}
}
@Override
public boolean hasNext() {
return !list.isEmpty();
}
@Override
public Node next() {
return list.poll();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}