TreeNodePreorderIterator.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-5.2.0).
03  * Copyright (c) 2007-2020 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.Deque;
27 import java.util.Iterator;
28 import java.util.NoSuchElementException;
29 
30 /**
31  * Preorder iterator of the tree.
32  *
33  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
34  @version 5.2
35  @since 3.9
36  */
37 final class TreeNodePreorderIterator<V, T extends Tree<V, T>>
38     implements Iterator<T>
39 {
40     private final Deque<Iterator<T>> _deque = new ArrayDeque<>();
41 
42     /**
43      * Create a new preorder iterator of the given tree {@code root}.
44      *
45      @param root the root node of the tree
46      @throws NullPointerException if the given {@code root} node is
47      *        {@code null}
48      */
49     TreeNodePreorderIterator(final T root) {
50         requireNonNull(root);
51         _deque.push(singletonList(root).iterator());
52     }
53 
54     @Override
55     public boolean hasNext() {
56         final Iterator<T> peek = _deque.peek();
57         return peek != null && peek.hasNext();
58     }
59 
60     @Override
61     public T next() {
62         final Iterator<T> it = _deque.peek();
63         if (it == null) {
64             throw new NoSuchElementException("No next element.");
65         }
66 
67         final T node = it.next();
68         if (!it.hasNext()) {
69             _deque.pop();
70         }
71 
72         final Iterator<T> children = node.childIterator();
73         if (children.hasNext()) {
74             _deque.push(children);
75         }
76 
77         return node;
78     }
79 }