Skip to content

Instantly share code, notes, and snippets.

@dhsrocha
Forked from konrad-garus/Tree.java
Last active April 2, 2025 09:06
Show Gist options
  • Save dhsrocha/972a48c40a24bfa34ec6614f222e7339 to your computer and use it in GitHub Desktop.
Save dhsrocha/972a48c40a24bfa34ec6614f222e7339 to your computer and use it in GitHub Desktop.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
final class Tree<T> {
private final List<Tree<T>> children = new LinkedList<>();
private final T value;
Tree(final T value, final List<Tree<T>> children) {
this.value = Objects.requireNonNull(value);
this.children.addAll(children);
}
@SafeVarargs
Tree(T value, Tree<T>... children) {
this(value, asList(children));
}
T value() {
return value;
}
List<Tree<T>> children() {
return Collections.unmodifiableList(this.children);
}
Stream<Tree<T>> flattened() {
return Stream.concat(
Stream.of(this),
this.children.stream().flatMap(Tree::flattened));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment