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