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;
028
029/**
030 * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees
031 * induced by this traverser.
032 *
033 * <p>For example, the tree
034 *
035 * <pre>{@code
036 *        h
037 *      / | \
038 *     /  e  \
039 *    d       g
040 *   /|\      |
041 *  / | \     f
042 * a  b  c
043 * }</pre>
044 *
045 * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order
046 * (hdegabcf).
047 *
048 * <p>Null nodes are strictly forbidden.
049 *
050 * <p><b>For Java 8 users:</b> Because this is an abstract class, not an interface, you can't use a
051 * lambda expression to extend it:
052 *
053 * <pre>{@code
054 * // won't work
055 * TreeTraverser<NodeType> traverser = node -> node.getChildNodes();
056 * }</pre>
057 *
058 * Instead, you can pass a lambda expression to the {@code using} factory method:
059 *
060 * <pre>{@code
061 * TreeTraverser<NodeType> traverser = TreeTraverser.using(node -> node.getChildNodes());
062 * }</pre>
063 *
064 * @author Louis Wasserman
065 * @since 15.0
066 * @deprecated Use {@link com.google.common.graph.Traverser} instead. All instance methods have
067 *     their equivalent on the result of {@code Traverser.forTree(tree)} where {@code tree}
068 *     implements {@code SuccessorsFunction}, which has a similar API as {@link #children} or can be
069 *     the same lambda function as passed into {@link #using(Function)}.
070 *     <p>This class is scheduled to be removed in April 2018.
071 */
072@Deprecated
073@Beta
074@GwtCompatible
075public abstract class TreeTraverser<T> {
076
077  /**
078   * Returns a tree traverser that uses the given function to navigate from a node to its children.
079   * This is useful if the function instance already exists, or so that you can supply a lambda
080   * expressions. If those circumstances don't apply, you probably don't need to use this; subclass
081   * {@code TreeTraverser} and implement its {@link #children} method directly.
082   *
083   * @since 20.0
084   * @deprecated Use {@link com.google.common.graph.Traverser#forTree} instead. If you are using a
085   *     lambda, these methods have exactly the same signature.
086   */
087  @Deprecated
088  public static <T> TreeTraverser<T> using(
089      final Function<T, ? extends Iterable<T>> nodeToChildrenFunction) {
090    checkNotNull(nodeToChildrenFunction);
091    return new TreeTraverser<T>() {
092      @Override
093      public Iterable<T> children(T root) {
094        return nodeToChildrenFunction.apply(root);
095      }
096    };
097  }
098
099  /** Returns the children of the specified node. Must not contain null. */
100  public abstract Iterable<T> children(T root);
101
102  /**
103   * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order traversal.
104   * That is, each node's subtrees are traversed after the node itself is returned.
105   *
106   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
107   * is in progress or when the iterators generated by {@link #children} are advanced.
108   *
109   * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPreOrder} instead, which has
110   *     the same behavior.
111   */
112  @Deprecated
113  public final FluentIterable<T> preOrderTraversal(final T root) {
114    checkNotNull(root);
115    return new FluentIterable<T>() {
116      @Override
117      public UnmodifiableIterator<T> iterator() {
118        return preOrderIterator(root);
119      }
120    };
121  }
122
123  UnmodifiableIterator<T> preOrderIterator(T root) {
124    return new PreOrderIterator(root);
125  }
126
127  private final class PreOrderIterator extends UnmodifiableIterator<T> {
128    private final Deque<Iterator<T>> stack;
129
130    PreOrderIterator(T root) {
131      this.stack = new ArrayDeque<>();
132      stack.addLast(Iterators.singletonIterator(checkNotNull(root)));
133    }
134
135    @Override
136    public boolean hasNext() {
137      return !stack.isEmpty();
138    }
139
140    @Override
141    public T next() {
142      Iterator<T> itr = stack.getLast(); // throws NSEE if empty
143      T result = checkNotNull(itr.next());
144      if (!itr.hasNext()) {
145        stack.removeLast();
146      }
147      Iterator<T> childItr = children(result).iterator();
148      if (childItr.hasNext()) {
149        stack.addLast(childItr);
150      }
151      return result;
152    }
153  }
154
155  /**
156   * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order
157   * traversal. That is, each node's subtrees are traversed before the node itself is returned.
158   *
159   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
160   * is in progress or when the iterators generated by {@link #children} are advanced.
161   *
162   * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPostOrder} instead, which
163   *     has the same behavior.
164   */
165  @Deprecated
166  public final FluentIterable<T> postOrderTraversal(final T root) {
167    checkNotNull(root);
168    return new FluentIterable<T>() {
169      @Override
170      public UnmodifiableIterator<T> iterator() {
171        return postOrderIterator(root);
172      }
173    };
174  }
175
176  UnmodifiableIterator<T> postOrderIterator(T root) {
177    return new PostOrderIterator(root);
178  }
179
180  private static final class PostOrderNode<T> {
181    final T root;
182    final Iterator<T> childIterator;
183
184    PostOrderNode(T root, Iterator<T> childIterator) {
185      this.root = checkNotNull(root);
186      this.childIterator = checkNotNull(childIterator);
187    }
188  }
189
190  private final class PostOrderIterator extends AbstractIterator<T> {
191    private final ArrayDeque<PostOrderNode<T>> stack;
192
193    PostOrderIterator(T root) {
194      this.stack = new ArrayDeque<>();
195      stack.addLast(expand(root));
196    }
197
198    @Override
199    protected T computeNext() {
200      while (!stack.isEmpty()) {
201        PostOrderNode<T> top = stack.getLast();
202        if (top.childIterator.hasNext()) {
203          T child = top.childIterator.next();
204          stack.addLast(expand(child));
205        } else {
206          stack.removeLast();
207          return top.root;
208        }
209      }
210      return endOfData();
211    }
212
213    private PostOrderNode<T> expand(T t) {
214      return new PostOrderNode<T>(t, children(t).iterator());
215    }
216  }
217
218  /**
219   * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first
220   * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on.
221   *
222   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
223   * is in progress or when the iterators generated by {@link #children} are advanced.
224   *
225   * @deprecated Use {@link com.google.common.graph.Traverser#breadthFirst} instead, which has the
226   *     same behavior.
227   */
228  @Deprecated
229  public final FluentIterable<T> breadthFirstTraversal(final T root) {
230    checkNotNull(root);
231    return new FluentIterable<T>() {
232      @Override
233      public UnmodifiableIterator<T> iterator() {
234        return new BreadthFirstIterator(root);
235      }
236    };
237  }
238
239  private final class BreadthFirstIterator extends UnmodifiableIterator<T>
240      implements PeekingIterator<T> {
241    private final Queue<T> queue;
242
243    BreadthFirstIterator(T root) {
244      this.queue = new ArrayDeque<T>();
245      queue.add(root);
246    }
247
248    @Override
249    public boolean hasNext() {
250      return !queue.isEmpty();
251    }
252
253    @Override
254    public T peek() {
255      return queue.element();
256    }
257
258    @Override
259    public T next() {
260      T result = queue.remove();
261      Iterables.addAll(queue, children(result));
262      return result;
263    }
264  }
265}