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