(In case you want to avoid the lengthy explanation, all I am looking for is a level order traversal for a generic-tree(n-ary tree) in java. The code supplied works and needs
The following seems to work. For extra credit, iteration can be done with an enhanced for loop, and aborted at any time. You might want to add access modifiers.
import java.util.*;
class NaryTree {
final int data;
final List children;
public NaryTree(int data, NaryTree... children) {
this.data = data;
this.children = Arrays.asList(children);
}
static class InOrderIterator implements Iterator {
final Queue queue = new LinkedList();
public InOrderIterator(NaryTree tree) {
queue.add(tree);
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
public Integer next() {
NaryTree node = queue.remove();
queue.addAll(node.children);
return node.data;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Iterable inOrderView = new Iterable() {
@Override
public Iterator iterator() {
return new InOrderIterator(NaryTree.this);
}
};
}
Test code:
public class Test {
public static void main(String[] args) throws Exception {
NaryTree tree = new NaryTree(100,
new NaryTree(90,
new NaryTree(20),
new NaryTree(30)
), new NaryTree(50,
new NaryTree(200),
new NaryTree(300)
), new NaryTree(70)
);
for (int x : tree.inOrderView) {
System.out.println(x);
}
}
}