TreeNodePostorderIterator.java
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.Objects.requireNonNull;
23 
24 import java.util.Collections;
25 import java.util.Iterator;
26 
27 /**
28  * Postorder iterator of the tree.
29  *
30  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
31  @version 3.9
32  @since 3.9
33  */
34 final class TreeNodePostorderIterator<V, T extends Tree<V, T>>
35     implements Iterator<T>
36 {
37 
38     private T _root;
39     private final Iterator<T> _children;
40     private Iterator<T> _subtree;
41 
42     /**
43      * Create a new postorder 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     TreeNodePostorderIterator(final T root) {
50         _root = requireNonNull(root);
51         _children = _root.childIterator();
52         _subtree = Collections.emptyIterator();
53     }
54 
55     @Override
56     public boolean hasNext() {
57         return _root != null;
58     }
59 
60     @Override
61     public T next() {
62         final T result;
63         if (_subtree.hasNext()) {
64             result = _subtree.next();
65         else if (_children.hasNext()) {
66             _subtree = new TreeNodePostorderIterator<>(_children.next());
67             result = _subtree.next();
68         else {
69             result = _root;
70             _root = null;
71         }
72 
73         return result;
74     }
75 
76 }