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 javax.annotation.CheckForNull; 030 031/** 032 * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees 033 * induced by this traverser. 034 * 035 * <p>For example, the tree 036 * 037 * <pre>{@code 038 * h 039 * / | \ 040 * / e \ 041 * d g 042 * /|\ | 043 * / | \ f 044 * a b c 045 * }</pre> 046 * 047 * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order 048 * (hdegabcf). 049 * 050 * <p>Null nodes are strictly forbidden. 051 * 052 * <p>Because this is an abstract class, not an interface, you can't use a lambda expression to 053 * implement it: 054 * 055 * <pre>{@code 056 * // won't work 057 * TreeTraverser<NodeType> traverser = node -> node.getChildNodes(); 058 * }</pre> 059 * 060 * Instead, you can pass a lambda expression to the {@code using} factory method: 061 * 062 * <pre>{@code 063 * TreeTraverser<NodeType> traverser = TreeTraverser.using(node -> node.getChildNodes()); 064 * }</pre> 065 * 066 * @author Louis Wasserman 067 * @since 15.0 068 * @deprecated Use {@link com.google.common.graph.Traverser} instead. All instance methods have 069 * their equivalent on the result of {@code Traverser.forTree(tree)} where {@code tree} 070 * implements {@code SuccessorsFunction}, which has a similar API as {@link #children} or can be 071 * the same lambda function as passed into {@link #using(Function)}. 072 * <p>This class is scheduled to be removed in October 2019. 073 */ 074// TODO(b/68134636): Remove by 2019-10 075@Deprecated 076@Beta 077@GwtCompatible 078@ElementTypesAreNonnullByDefault 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 } 128 129 UnmodifiableIterator<T> preOrderIterator(T root) { 130 return new PreOrderIterator(root); 131 } 132 133 private final class PreOrderIterator extends UnmodifiableIterator<T> { 134 private final Deque<Iterator<T>> stack; 135 136 PreOrderIterator(T root) { 137 this.stack = new ArrayDeque<>(); 138 stack.addLast(singletonIterator(checkNotNull(root))); 139 } 140 141 @Override 142 public boolean hasNext() { 143 return !stack.isEmpty(); 144 } 145 146 @Override 147 public T next() { 148 Iterator<T> itr = stack.getLast(); // throws NSEE if empty 149 T result = checkNotNull(itr.next()); 150 if (!itr.hasNext()) { 151 stack.removeLast(); 152 } 153 Iterator<T> childItr = children(result).iterator(); 154 if (childItr.hasNext()) { 155 stack.addLast(childItr); 156 } 157 return result; 158 } 159 } 160 161 /** 162 * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order 163 * traversal. That is, each node's subtrees are traversed before the node itself is returned. 164 * 165 * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration 166 * is in progress or when the iterators generated by {@link #children} are advanced. 167 * 168 * @deprecated Use {@link com.google.common.graph.Traverser#depthFirstPostOrder} instead, which 169 * has the same behavior. 170 */ 171 @Deprecated 172 public final FluentIterable<T> postOrderTraversal(final T root) { 173 checkNotNull(root); 174 return new FluentIterable<T>() { 175 @Override 176 public UnmodifiableIterator<T> iterator() { 177 return postOrderIterator(root); 178 } 179 }; 180 } 181 182 UnmodifiableIterator<T> postOrderIterator(T root) { 183 return new PostOrderIterator(root); 184 } 185 186 private static final class PostOrderNode<T> { 187 final T root; 188 final Iterator<T> childIterator; 189 190 PostOrderNode(T root, Iterator<T> childIterator) { 191 this.root = checkNotNull(root); 192 this.childIterator = checkNotNull(childIterator); 193 } 194 } 195 196 private final class PostOrderIterator extends AbstractIterator<T> { 197 private final ArrayDeque<PostOrderNode<T>> stack; 198 199 PostOrderIterator(T root) { 200 this.stack = new ArrayDeque<>(); 201 stack.addLast(expand(root)); 202 } 203 204 @Override 205 @CheckForNull 206 protected T computeNext() { 207 while (!stack.isEmpty()) { 208 PostOrderNode<T> top = stack.getLast(); 209 if (top.childIterator.hasNext()) { 210 T child = top.childIterator.next(); 211 stack.addLast(expand(child)); 212 } else { 213 stack.removeLast(); 214 return top.root; 215 } 216 } 217 return endOfData(); 218 } 219 220 private PostOrderNode<T> expand(T t) { 221 return new PostOrderNode<>(t, children(t).iterator()); 222 } 223 } 224 225 /** 226 * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first 227 * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on. 228 * 229 * <p>No guarantees are made about the behavior of the traversal when nodes change while iteration 230 * is in progress or when the iterators generated by {@link #children} are advanced. 231 * 232 * @deprecated Use {@link com.google.common.graph.Traverser#breadthFirst} instead, which has the 233 * same behavior. 234 */ 235 @Deprecated 236 public final FluentIterable<T> breadthFirstTraversal(final T root) { 237 checkNotNull(root); 238 return new FluentIterable<T>() { 239 @Override 240 public UnmodifiableIterator<T> iterator() { 241 return new BreadthFirstIterator(root); 242 } 243 }; 244 } 245 246 private final class BreadthFirstIterator extends UnmodifiableIterator<T> 247 implements PeekingIterator<T> { 248 private final Queue<T> queue; 249 250 BreadthFirstIterator(T root) { 251 this.queue = new ArrayDeque<>(); 252 queue.add(root); 253 } 254 255 @Override 256 public boolean hasNext() { 257 return !queue.isEmpty(); 258 } 259 260 @Override 261 public T peek() { 262 return queue.element(); 263 } 264 265 @Override 266 public T next() { 267 T result = queue.remove(); 268 Iterables.addAll(queue, children(result)); 269 return result; 270 } 271 } 272}