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 org.jspecify.annotations.Nullable; 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 079public abstract class TreeTraverser<T> { 080 /** Constructor for use by subclasses. */ 081 public TreeTraverser() {} 082 083 /** 084 * Returns a tree traverser that uses the given function to navigate from a node to its children. 085 * This is useful if the function instance already exists, or so that you can supply a lambda 086 * expressions. If those circumstances don't apply, you probably don't need to use this; subclass 087 * {@code TreeTraverser} and implement its {@link #children} method directly. 088 * 089 * @since 20.0 090 * @deprecated Use {@link com.google.common.graph.Traverser#forTree} instead. If you are using a 091 * lambda, these methods have exactly the same signature. 092 */ 093 @Deprecated 094 public static <T> TreeTraverser<T> using( 095 final Function<T, ? extends Iterable<T>> nodeToChildrenFunction) { 096 checkNotNull(nodeToChildrenFunction); 097 return new TreeTraverser<T>() { 098 @Override 099 public Iterable<T> children(T root) { 100 return nodeToChildrenFunction.apply(root); 101 } 102 }; 103 } 104 105 /** Returns the children of the specified node. Must not contain null. */ 106 public abstract Iterable<T> children(T root); 107 108 /** 109 * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order traversal. 110 * That is, each node's subtrees are traversed after the node itself is returned. 111 * 112 * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration 113 * is in progress or when the iterators generated by {@link #children} are advanced. 114 * 115 * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPreOrder} instead, which has 116 * the same behavior. 117 */ 118 @Deprecated 119 public final FluentIterable<T> preOrderTraversal(final T root) { 120 checkNotNull(root); 121 return new FluentIterable<T>() { 122 @Override 123 public UnmodifiableIterator<T> iterator() { 124 return preOrderIterator(root); 125 } 126 127 @Override 128 public void forEach(Consumer<? super T> action) { 129 checkNotNull(action); 130 new Consumer<T>() { 131 @Override 132 public void accept(T t) { 133 action.accept(t); 134 children(t).forEach(this); 135 } 136 }.accept(root); 137 } 138 }; 139 } 140 141 UnmodifiableIterator<T> preOrderIterator(T root) { 142 return new PreOrderIterator(root); 143 } 144 145 private final class PreOrderIterator extends UnmodifiableIterator<T> { 146 private final Deque<Iterator<T>> stack; 147 148 PreOrderIterator(T root) { 149 this.stack = new ArrayDeque<>(); 150 stack.addLast(singletonIterator(checkNotNull(root))); 151 } 152 153 @Override 154 public boolean hasNext() { 155 return !stack.isEmpty(); 156 } 157 158 @Override 159 public T next() { 160 Iterator<T> itr = stack.getLast(); // throws NSEE if empty 161 T result = checkNotNull(itr.next()); 162 if (!itr.hasNext()) { 163 stack.removeLast(); 164 } 165 Iterator<T> childItr = children(result).iterator(); 166 if (childItr.hasNext()) { 167 stack.addLast(childItr); 168 } 169 return result; 170 } 171 } 172 173 /** 174 * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order 175 * traversal. That is, each node's subtrees are traversed before the node itself is returned. 176 * 177 * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration 178 * is in progress or when the iterators generated by {@link #children} are advanced. 179 * 180 * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPostOrder} instead, which 181 * has the same behavior. 182 */ 183 @Deprecated 184 public final FluentIterable<T> postOrderTraversal(final T root) { 185 checkNotNull(root); 186 return new FluentIterable<T>() { 187 @Override 188 public UnmodifiableIterator<T> iterator() { 189 return postOrderIterator(root); 190 } 191 192 @Override 193 public void forEach(Consumer<? super T> action) { 194 checkNotNull(action); 195 new Consumer<T>() { 196 @Override 197 public void accept(T t) { 198 children(t).forEach(this); 199 action.accept(t); 200 } 201 }.accept(root); 202 } 203 }; 204 } 205 206 UnmodifiableIterator<T> postOrderIterator(T root) { 207 return new PostOrderIterator(root); 208 } 209 210 private static final class PostOrderNode<T> { 211 final T root; 212 final Iterator<T> childIterator; 213 214 PostOrderNode(T root, Iterator<T> childIterator) { 215 this.root = checkNotNull(root); 216 this.childIterator = checkNotNull(childIterator); 217 } 218 } 219 220 private final class PostOrderIterator extends AbstractIterator<T> { 221 private final ArrayDeque<PostOrderNode<T>> stack; 222 223 PostOrderIterator(T root) { 224 this.stack = new ArrayDeque<>(); 225 stack.addLast(expand(root)); 226 } 227 228 @Override 229 protected @Nullable 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}