package com.github.javachat.streems.spliterators;

import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * A spliterator for breadth-first traversal
 *
 * @param <T> type of the nodes in the tree
 */
public final class BreadthFirstSpliterator<T>
    extends NaryTreeSpliterator<T>
{
    private final Deque<Iterator<T>> deque = new ArrayDeque<>();

    public BreadthFirstSpliterator(final T root,
        final Function<T, Iterator<T>> fn)
    {
        super(root, fn);
        deque.addFirst(Collections.singleton(root).iterator());
    }

    @SuppressWarnings("TailRecursion")
    @Override
    public boolean tryAdvance(final Consumer<? super T> action)
    {
        final Iterator<T> iterator;
        final T element;

        if (deque.isEmpty())
            return false;

        iterator = deque.getFirst();
        if (!iterator.hasNext()) {
            deque.removeFirst();
            return tryAdvance(action);
        }

        element = iterator.next();
        deque.add(fn.apply(element));
        action.accept(element);
        return true;
    }
}

@@ -801,22 +801,16 @@
         
-final 
 Iterator
@@ -831,22 +831,16 @@
         
-final 
 T elemen
@@ -851,20 +851,24 @@
         
-if
+while
  (
+!
 deque.is
@@ -879,36 +879,15 @@
 y())
+ %7B
 %0A    
-        return false;%0A%0A
     
@@ -927,16 +927,20 @@
         
+    
 if (!ite
@@ -966,24 +966,28 @@
             
+   
+ 
 deque.remove
@@ -1011,35 +1011,26 @@
     
-return tryAdvance(action);%0A
+    continue;%0A    
     
@@ -1031,25 +1031,28 @@
           %7D%0A
-%0A
+    
         elem
@@ -1070,24 +1070,28 @@
 tor.next();%0A
+    
         dequ
@@ -1124,16 +1124,20 @@
         
+    
 action.a
@@ -1152,16 +1152,20 @@
 ement);%0A
+    
         
@@ -1173,20 +1173,52 @@
 eturn true;%0A
+        %7D%0A        return false;%0A
     %7D%0A%7D%0A

replace with a loop