01 /*
02 * Java Genetic Algorithm Library (jenetics-5.1.0).
03 * Copyright (c) 2007-2019 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext.util;
21
22 import static java.util.Collections.singletonList;
23 import static java.util.Objects.requireNonNull;
24
25 import java.util.ArrayDeque;
26 import java.util.Iterator;
27 import java.util.NoSuchElementException;
28 import java.util.Queue;
29
30 /**
31 * Breadth-first search (BFS) traversing of the tree. It starts at the tree root
32 * and explores the neighbor nodes first, before moving to the next level
33 * neighbors.
34 *
35 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
36 * @version 3.9
37 * @since 3.9
38 */
39 final class TreeNodeBreadthFirstIterator<V, T extends Tree<V, T>>
40 implements Iterator<T>
41 {
42 private final Queue<Iterator<T>> _queue = new ArrayDeque<>();
43
44 /**
45 * Create a new breath-first iterator from the given {@code root} element.
46 *
47 * @param root the root element of the tree
48 * @throws NullPointerException if the given {@code root} node is
49 * {@code null}
50 */
51 TreeNodeBreadthFirstIterator(final T root) {
52 requireNonNull(root);
53 _queue.add(singletonList(root).iterator());
54 }
55
56 @Override
57 public boolean hasNext() {
58 final Iterator<T> peek = _queue.peek();
59 return peek != null && peek.hasNext();
60 }
61
62 @Override
63 public T next() {
64 final Iterator<T> it = _queue.peek();
65 if (it == null) {
66 throw new NoSuchElementException("No next element.");
67 }
68
69 final T node = it.next();
70 if (!it.hasNext()) {
71 _queue.poll();
72 }
73
74 final Iterator<T> children = node.childIterator();
75 if (children.hasNext()) {
76 _queue.add(children);
77 }
78
79 return node;
80 }
81
82 }
|