View Javadoc
1   /*
2    * Copyright (C) 2012 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.Beta;
22  import com.google.common.annotations.GwtCompatible;
23  import com.google.common.base.Function;
24  import java.util.ArrayDeque;
25  import java.util.Deque;
26  import java.util.Iterator;
27  import java.util.Queue;
28  import java.util.function.Consumer;
29  
30  /**
31   * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees
32   * induced by this traverser.
33   *
34   * <p>For example, the tree
35   *
36   * <pre>{@code
37   *        h
38   *      / | \
39   *     /  e  \
40   *    d       g
41   *   /|\      |
42   *  / | \     f
43   * a  b  c
44   * }</pre>
45   *
46   * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order
47   * (hdegabcf).
48   *
49   * <p>Null nodes are strictly forbidden.
50   *
51   * <p><b>For Java 8 users:</b> Because this is an abstract class, not an interface, you can't use a
52   * lambda expression to extend it:
53   *
54   * <pre>{@code
55   * // won't work
56   * TreeTraverser<NodeType> traverser = node -> node.getChildNodes();
57   * }</pre>
58   *
59   * Instead, you can pass a lambda expression to the {@code using} factory method:
60   *
61   * <pre>{@code
62   * TreeTraverser<NodeType> traverser = TreeTraverser.using(node -> node.getChildNodes());
63   * }</pre>
64   *
65   * @author Louis Wasserman
66   * @since 15.0
67   */
68  @Beta
69  @GwtCompatible
70  public abstract class TreeTraverser<T> {
71  
72    /**
73     * Returns a tree traverser that uses the given function to navigate from a node to its children.
74     * This is useful if the function instance already exists, or so that you can supply a lambda
75     * expressions. If those circumstances don't apply, you probably don't need to use this; subclass
76     * {@code TreeTraverser} and implement its {@link #children} method directly.
77     *
78     * @since 20.0
79     */
80    public static <T> TreeTraverser<T> using(
81        final Function<T, ? extends Iterable<T>> nodeToChildrenFunction) {
82      checkNotNull(nodeToChildrenFunction);
83      return new TreeTraverser<T>() {
84        @Override
85        public Iterable<T> children(T root) {
86          return nodeToChildrenFunction.apply(root);
87        }
88      };
89    }
90  
91    /**
92     * Returns the children of the specified node.  Must not contain null.
93     */
94    public abstract Iterable<T> children(T root);
95  
96    /**
97     * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order
98     * traversal. That is, each node's subtrees are traversed after the node itself is returned.
99     *
100    * <p>No guarantees are made about the behavior of the traversal when nodes change while
101    * iteration is in progress or when the iterators generated by {@link #children} are advanced.
102    */
103   public final FluentIterable<T> preOrderTraversal(final T root) {
104     checkNotNull(root);
105     return new FluentIterable<T>() {
106       @Override
107       public UnmodifiableIterator<T> iterator() {
108         return preOrderIterator(root);
109       }
110 
111       @Override
112       public void forEach(Consumer<? super T> action) {
113         checkNotNull(action);
114         new Consumer<T>() {
115           @Override
116           public void accept(T t) {
117             action.accept(t);
118             children(t).forEach(this);
119           }
120         }.accept(root);
121       }
122     };
123   }
124 
125   // overridden in BinaryTreeTraverser
126   UnmodifiableIterator<T> preOrderIterator(T root) {
127     return new PreOrderIterator(root);
128   }
129 
130   private final class PreOrderIterator extends UnmodifiableIterator<T> {
131     private final Deque<Iterator<T>> stack;
132 
133     PreOrderIterator(T root) {
134       this.stack = new ArrayDeque<>();
135       stack.addLast(Iterators.singletonIterator(checkNotNull(root)));
136     }
137 
138     @Override
139     public boolean hasNext() {
140       return !stack.isEmpty();
141     }
142 
143     @Override
144     public T next() {
145       Iterator<T> itr = stack.getLast(); // throws NSEE if empty
146       T result = checkNotNull(itr.next());
147       if (!itr.hasNext()) {
148         stack.removeLast();
149       }
150       Iterator<T> childItr = children(result).iterator();
151       if (childItr.hasNext()) {
152         stack.addLast(childItr);
153       }
154       return result;
155     }
156   }
157 
158   /**
159    * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order
160    * traversal. That is, each node's subtrees are traversed before the node itself is returned.
161    *
162    * <p>No guarantees are made about the behavior of the traversal when nodes change while
163    * iteration is in progress or when the iterators generated by {@link #children} are advanced.
164    */
165   public final FluentIterable<T> postOrderTraversal(final T root) {
166     checkNotNull(root);
167     return new FluentIterable<T>() {
168       @Override
169       public UnmodifiableIterator<T> iterator() {
170         return postOrderIterator(root);
171       }
172 
173       @Override
174       public void forEach(Consumer<? super T> action) {
175         checkNotNull(action);
176         new Consumer<T>() {
177           @Override
178           public void accept(T t) {
179             children(t).forEach(this);
180             action.accept(t);
181           }
182         }.accept(root);
183       }
184     };
185   }
186 
187   // overridden in BinaryTreeTraverser
188   UnmodifiableIterator<T> postOrderIterator(T root) {
189     return new PostOrderIterator(root);
190   }
191 
192   private static final class PostOrderNode<T> {
193     final T root;
194     final Iterator<T> childIterator;
195 
196     PostOrderNode(T root, Iterator<T> childIterator) {
197       this.root = checkNotNull(root);
198       this.childIterator = checkNotNull(childIterator);
199     }
200   }
201 
202   private final class PostOrderIterator extends AbstractIterator<T> {
203     private final ArrayDeque<PostOrderNode<T>> stack;
204 
205     PostOrderIterator(T root) {
206       this.stack = new ArrayDeque<>();
207       stack.addLast(expand(root));
208     }
209 
210     @Override
211     protected T computeNext() {
212       while (!stack.isEmpty()) {
213         PostOrderNode<T> top = stack.getLast();
214         if (top.childIterator.hasNext()) {
215           T child = top.childIterator.next();
216           stack.addLast(expand(child));
217         } else {
218           stack.removeLast();
219           return top.root;
220         }
221       }
222       return endOfData();
223     }
224 
225     private PostOrderNode<T> expand(T t) {
226       return new PostOrderNode<T>(t, children(t).iterator());
227     }
228   }
229 
230   /**
231    * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first
232    * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on.
233    *
234    * <p>No guarantees are made about the behavior of the traversal when nodes change while
235    * iteration is in progress or when the iterators generated by {@link #children} are advanced.
236    */
237   public final FluentIterable<T> breadthFirstTraversal(final T root) {
238     checkNotNull(root);
239     return new FluentIterable<T>() {
240       @Override
241       public UnmodifiableIterator<T> iterator() {
242         return new BreadthFirstIterator(root);
243       }
244     };
245   }
246 
247   private final class BreadthFirstIterator extends UnmodifiableIterator<T>
248       implements PeekingIterator<T> {
249     private final Queue<T> queue;
250 
251     BreadthFirstIterator(T root) {
252       this.queue = new ArrayDeque<T>();
253       queue.add(root);
254     }
255 
256     @Override
257     public boolean hasNext() {
258       return !queue.isEmpty();
259     }
260 
261     @Override
262     public T peek() {
263       return queue.element();
264     }
265 
266     @Override
267     public T next() {
268       T result = queue.remove();
269       Iterables.addAll(queue, children(result));
270       return result;
271     }
272   }
273 }