com.link_intersystems.graph.tree.DepthFirstTreeModelIterable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lis-commons-graph Show documentation
Show all versions of lis-commons-graph Show documentation
Link Intersystems Commons Graph (lis-commons-graph) is a collection of reusable software components
that provide support for graph and tree related programming tasks, such as models and search algorithms.
package com.link_intersystems.graph.tree;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.util.stream.Stream;
/**
* @author René Link {@literal }
*/
public class DepthFirstTreeModelIterable extends AbstractTreeModelIterable {
public DepthFirstTreeModelIterable(TreeModel treeModel, T rootElement) {
super(treeModel, rootElement);
}
@Override
protected Iterator createIterator(TreeModel treeModel, T rootElement) {
Stack stack = new Stack<>();
stack.push(rootElement);
return new Iterator() {
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T current = stack.pop();
Stream extends T> children = treeModel.getChildren(current);
int headIndex = stack.size();
children.forEach(c -> stack.add(headIndex, c));
return current;
}
};
}
}