public void traverse(Node root){
ArrayDeque<Node> queue = new ArrayDeque<Node>();
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
how would I get addAll(nl)
to add the entire collection(List<Node>
) to the front of the queue?
There is nothing built-in. But it is simple to emulate - just iterate the list in reverse order and add the elements. That way they will end up in the queue in the right order.
Other ways to iterate backwards are:
LinkedList
's descending iteratorCollections.reverse(..)
Pick one which fits your case.