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 October 2019. 071 */ 072// TODO(b/68134636): Remove by 2019-10 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 } 123 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 UnmodifiableIterator<T> postOrderIterator(T root) { 178 return new PostOrderIterator(root); 179 } 180 181 private static final class PostOrderNode<T> { 182 final T root; 183 final Iterator<T> childIterator; 184 185 PostOrderNode(T root, Iterator<T> childIterator) { 186 this.root = checkNotNull(root); 187 this.childIterator = checkNotNull(childIterator); 188 } 189 } 190 191 private final class PostOrderIterator extends AbstractIterator<T> { 192 private final ArrayDeque<PostOrderNode<T>> stack; 193 194 PostOrderIterator(T root) { 195 this.stack = new ArrayDeque<>(); 196 stack.addLast(expand(root)); 197 } 198 199 @Override 200 protected T computeNext() { 201 while (!stack.isEmpty()) { 202 PostOrderNode<T> top = stack.getLast(); 203 if (top.childIterator.hasNext()) { 204 T child = top.childIterator.next(); 205 stack.addLast(expand(child)); 206 } else { 207 stack.removeLast(); 208 return top.root; 209 } 210 } 211 return endOfData(); 212 } 213 214 private PostOrderNode<T> expand(T t) { 215 return new PostOrderNode<T>(t, children(t).iterator()); 216 } 217 } 218 219 /** 220 * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first 221 * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on. 222 * 223 * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration 224 * is in progress or when the iterators generated by {@link #children} are advanced. 225 * 226 * @deprecated Use {@link com.google.common.graph.Traverser#breadthFirst} instead, which has the 227 * same behavior. 228 */ 229 @Deprecated 230 public final FluentIterable<T> breadthFirstTraversal(final T root) { 231 checkNotNull(root); 232 return new FluentIterable<T>() { 233 @Override 234 public UnmodifiableIterator<T> iterator() { 235 return new BreadthFirstIterator(root); 236 } 237 }; 238 } 239 240 private final class BreadthFirstIterator extends UnmodifiableIterator<T> 241 implements PeekingIterator<T> { 242 private final Queue<T> queue; 243 244 BreadthFirstIterator(T root) { 245 this.queue = new ArrayDeque<T>(); 246 queue.add(root); 247 } 248 249 @Override 250 public boolean hasNext() { 251 return !queue.isEmpty(); 252 } 253 254 @Override 255 public T peek() { 256 return queue.element(); 257 } 258 259 @Override 260 public T next() { 261 T result = queue.remove(); 262 Iterables.addAll(queue, children(result)); 263 return result; 264 } 265 } 266}