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 January 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  // overridden in BinaryTreeTraverser
124  UnmodifiableIterator<T> preOrderIterator(T root) {
125    return new PreOrderIterator(root);
126  }
127
128  private final class PreOrderIterator extends UnmodifiableIterator<T> {
129    private final Deque<Iterator<T>> stack;
130
131    PreOrderIterator(T root) {
132      this.stack = new ArrayDeque<>();
133      stack.addLast(Iterators.singletonIterator(checkNotNull(root)));
134    }
135
136    @Override
137    public boolean hasNext() {
138      return !stack.isEmpty();
139    }
140
141    @Override
142    public T next() {
143      Iterator<T> itr = stack.getLast(); // throws NSEE if empty
144      T result = checkNotNull(itr.next());
145      if (!itr.hasNext()) {
146        stack.removeLast();
147      }
148      Iterator<T> childItr = children(result).iterator();
149      if (childItr.hasNext()) {
150        stack.addLast(childItr);
151      }
152      return result;
153    }
154  }
155
156  /**
157   * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order
158   * traversal. That is, each node's subtrees are traversed before the node itself is returned.
159   *
160   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
161   * is in progress or when the iterators generated by {@link #children} are advanced.
162   *
163   * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPostOrder} instead, which
164   *     has the same behavior.
165   */
166  @Deprecated
167  public final FluentIterable<T> postOrderTraversal(final T root) {
168    checkNotNull(root);
169    return new FluentIterable<T>() {
170      @Override
171      public UnmodifiableIterator<T> iterator() {
172        return postOrderIterator(root);
173      }
174    };
175  }
176
177  // overridden in BinaryTreeTraverser
178  UnmodifiableIterator<T> postOrderIterator(T root) {
179    return new PostOrderIterator(root);
180  }
181
182  private static final class PostOrderNode<T> {
183    final T root;
184    final Iterator<T> childIterator;
185
186    PostOrderNode(T root, Iterator<T> childIterator) {
187      this.root = checkNotNull(root);
188      this.childIterator = checkNotNull(childIterator);
189    }
190  }
191
192  private final class PostOrderIterator extends AbstractIterator<T> {
193    private final ArrayDeque<PostOrderNode<T>> stack;
194
195    PostOrderIterator(T root) {
196      this.stack = new ArrayDeque<>();
197      stack.addLast(expand(root));
198    }
199
200    @Override
201    protected T computeNext() {
202      while (!stack.isEmpty()) {
203        PostOrderNode<T> top = stack.getLast();
204        if (top.childIterator.hasNext()) {
205          T child = top.childIterator.next();
206          stack.addLast(expand(child));
207        } else {
208          stack.removeLast();
209          return top.root;
210        }
211      }
212      return endOfData();
213    }
214
215    private PostOrderNode<T> expand(T t) {
216      return new PostOrderNode<T>(t, children(t).iterator());
217    }
218  }
219
220  /**
221   * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first
222   * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on.
223   *
224   * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration
225   * is in progress or when the iterators generated by {@link #children} are advanced.
226   *
227   * @deprecated Use {@link com.google.common.graph.Traverser#breadthFirst} instead, which has the
228   *     same behavior.
229   */
230  @Deprecated
231  public final FluentIterable<T> breadthFirstTraversal(final T root) {
232    checkNotNull(root);
233    return new FluentIterable<T>() {
234      @Override
235      public UnmodifiableIterator<T> iterator() {
236        return new BreadthFirstIterator(root);
237      }
238    };
239  }
240
241  private final class BreadthFirstIterator extends UnmodifiableIterator<T>
242      implements PeekingIterator<T> {
243    private final Queue<T> queue;
244
245    BreadthFirstIterator(T root) {
246      this.queue = new ArrayDeque<T>();
247      queue.add(root);
248    }
249
250    @Override
251    public boolean hasNext() {
252      return !queue.isEmpty();
253    }
254
255    @Override
256    public T peek() {
257      return queue.element();
258    }
259
260    @Override
261    public T next() {
262      T result = queue.remove();
263      Iterables.addAll(queue, children(result));
264      return result;
265    }
266  }
267}