001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.base.Function;
024import java.util.ArrayDeque;
025import java.util.Deque;
026import java.util.Iterator;
027import java.util.Queue;
028import java.util.function.Consumer;
029
030/**
031 * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees
032 * induced by this traverser.
033 *
034 * <p>For example, the tree
035 *
036 * <pre>{@code
037 *        h
038 *      / | \
039 *     /  e  \
040 *    d       g
041 *   /|\      |
042 *  / | \     f
043 * a  b  c
044 * }</pre>
045 *
046 * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order
047 * (hdegabcf).
048 *
049 * <p>Null nodes are strictly forbidden.
050 *
051 * <p><b>For Java 8 users:</b> Because this is an abstract class, not an interface, you can't use a
052 * lambda expression to extend it:
053 *
054 * <pre>{@code
055 * // won't work
056 * TreeTraverser<NodeType> traverser = node -> node.getChildNodes();
057 * }</pre>
058 *
059 * Instead, you can pass a lambda expression to the {@code using} factory method:
060 *
061 * <pre>{@code
062 * TreeTraverser<NodeType> traverser = TreeTraverser.using(node -> node.getChildNodes());
063 * }</pre>
064 *
065 * @author Louis Wasserman
066 * @since 15.0
067 * @deprecated Use {@link com.google.common.graph.Traverser} instead. All instance methods have
068 *     their equivalent on the result of {@code Traverser.forTree(tree)} where {@code tree}
069 *     implements {@code SuccessorsFunction}, which has a similar API as {@link #children} or can be
070 *     the same lambda function as passed into {@link #using(Function)}.
071 *     <p>This class is scheduled to be removed in January 2018.
072 */
073@Deprecated
074@Beta
075@GwtCompatible
076public abstract class TreeTraverser<T> {
077
078  /**
079   * Returns a tree traverser that uses the given function to navigate from a node to its children.
080   * This is useful if the function instance already exists, or so that you can supply a lambda
081   * expressions. If those circumstances don't apply, you probably don't need to use this; subclass
082   * {@code TreeTraverser} and implement its {@link #children} method directly.
083   *
084   * @since 20.0
085   * @deprecated Use {@link com.google.common.graph.Traverser#forTree} instead. If you are using a
086   *     lambda, these methods have exactly the same signature.
087   */
088  @Deprecated
089  public static <T> TreeTraverser<T> using(
090      final Function<T, ? extends Iterable<T>> nodeToChildrenFunction) {
091    checkNotNull(nodeToChildrenFunction);
092    return new TreeTraverser<T>() {
093      @Override
094      public Iterable<T> children(T root) {
095        return nodeToChildrenFunction.apply(root);
096      }
097    };
098  }
099
100  /**
101   * Returns the children of the specified node.  Must not contain null.
102   */
103  public abstract Iterable<T> children(T root);
104
105  /**
106   * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order traversal.
107   * That is, each node's subtrees are traversed after the node itself is returned.
108   *
109   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
110   * is in progress or when the iterators generated by {@link #children} are advanced.
111   *
112   * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPreOrder} instead, which has
113   *     the same behavior.
114   */
115  @Deprecated
116  public final FluentIterable<T> preOrderTraversal(final T root) {
117    checkNotNull(root);
118    return new FluentIterable<T>() {
119      @Override
120      public UnmodifiableIterator<T> iterator() {
121        return preOrderIterator(root);
122      }
123
124      @Override
125      public void forEach(Consumer<? super T> action) {
126        checkNotNull(action);
127        new Consumer<T>() {
128          @Override
129          public void accept(T t) {
130            action.accept(t);
131            children(t).forEach(this);
132          }
133        }.accept(root);
134      }
135    };
136  }
137
138  // overridden in BinaryTreeTraverser
139  UnmodifiableIterator<T> preOrderIterator(T root) {
140    return new PreOrderIterator(root);
141  }
142
143  private final class PreOrderIterator extends UnmodifiableIterator<T> {
144    private final Deque<Iterator<T>> stack;
145
146    PreOrderIterator(T root) {
147      this.stack = new ArrayDeque<>();
148      stack.addLast(Iterators.singletonIterator(checkNotNull(root)));
149    }
150
151    @Override
152    public boolean hasNext() {
153      return !stack.isEmpty();
154    }
155
156    @Override
157    public T next() {
158      Iterator<T> itr = stack.getLast(); // throws NSEE if empty
159      T result = checkNotNull(itr.next());
160      if (!itr.hasNext()) {
161        stack.removeLast();
162      }
163      Iterator<T> childItr = children(result).iterator();
164      if (childItr.hasNext()) {
165        stack.addLast(childItr);
166      }
167      return result;
168    }
169  }
170
171  /**
172   * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order
173   * traversal. That is, each node's subtrees are traversed before the node itself is returned.
174   *
175   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
176   * is in progress or when the iterators generated by {@link #children} are advanced.
177   *
178   * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPostOrder} instead, which
179   *     has the same behavior.
180   */
181  @Deprecated
182  public final FluentIterable<T> postOrderTraversal(final T root) {
183    checkNotNull(root);
184    return new FluentIterable<T>() {
185      @Override
186      public UnmodifiableIterator<T> iterator() {
187        return postOrderIterator(root);
188      }
189
190      @Override
191      public void forEach(Consumer<? super T> action) {
192        checkNotNull(action);
193        new Consumer<T>() {
194          @Override
195          public void accept(T t) {
196            children(t).forEach(this);
197            action.accept(t);
198          }
199        }.accept(root);
200      }
201    };
202  }
203
204  // overridden in BinaryTreeTraverser
205  UnmodifiableIterator<T> postOrderIterator(T root) {
206    return new PostOrderIterator(root);
207  }
208
209  private static final class PostOrderNode<T> {
210    final T root;
211    final Iterator<T> childIterator;
212
213    PostOrderNode(T root, Iterator<T> childIterator) {
214      this.root = checkNotNull(root);
215      this.childIterator = checkNotNull(childIterator);
216    }
217  }
218
219  private final class PostOrderIterator extends AbstractIterator<T> {
220    private final ArrayDeque<PostOrderNode<T>> stack;
221
222    PostOrderIterator(T root) {
223      this.stack = new ArrayDeque<>();
224      stack.addLast(expand(root));
225    }
226
227    @Override
228    protected T computeNext() {
229      while (!stack.isEmpty()) {
230        PostOrderNode<T> top = stack.getLast();
231        if (top.childIterator.hasNext()) {
232          T child = top.childIterator.next();
233          stack.addLast(expand(child));
234        } else {
235          stack.removeLast();
236          return top.root;
237        }
238      }
239      return endOfData();
240    }
241
242    private PostOrderNode<T> expand(T t) {
243      return new PostOrderNode<T>(t, children(t).iterator());
244    }
245  }
246
247  /**
248   * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first
249   * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on.
250   *
251   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
252   * is in progress or when the iterators generated by {@link #children} are advanced.
253   *
254   * @deprecated Use {@link com.google.common.graph.Traverser#breadthFirst} instead, which has the
255   *     same behavior.
256   */
257  @Deprecated
258  public final FluentIterable<T> breadthFirstTraversal(final T root) {
259    checkNotNull(root);
260    return new FluentIterable<T>() {
261      @Override
262      public UnmodifiableIterator<T> iterator() {
263        return new BreadthFirstIterator(root);
264      }
265    };
266  }
267
268  private final class BreadthFirstIterator extends UnmodifiableIterator<T>
269      implements PeekingIterator<T> {
270    private final Queue<T> queue;
271
272    BreadthFirstIterator(T root) {
273      this.queue = new ArrayDeque<T>();
274      queue.add(root);
275    }
276
277    @Override
278    public boolean hasNext() {
279      return !queue.isEmpty();
280    }
281
282    @Override
283    public T peek() {
284      return queue.element();
285    }
286
287    @Override
288    public T next() {
289      T result = queue.remove();
290      Iterables.addAll(queue, children(result));
291      return result;
292    }
293  }
294}