Created
February 23, 2015 16:22
-
-
Save jooyunghan/ba5812d8eccb4dd1147f to your computer and use it in GitHub Desktop.
An example for RoseTree in Java 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.List; | |
| import java.util.Arrays; | |
| public class RoseTree<T> { | |
| private final T value; | |
| private final List<RoseTree<T>> children; | |
| public RoseTree(T value, List<RoseTree<T>> children) { | |
| this.value = value; | |
| this.children = children; | |
| } | |
| public int count() { | |
| return 1 + children.stream().mapToInt(RoseTree::count).sum(); | |
| } | |
| public int countLeaves() { | |
| if (children.isEmpty()) return 1; | |
| return children.stream().mapToInt(RoseTree::countLeaves).sum(); | |
| } | |
| public int height() { | |
| return 1 + children.stream().mapToInt(RoseTree::height).max().orElse(0); | |
| } | |
| @SafeVarargs | |
| private static <T> RoseTree<T> rose(T value, RoseTree<T>... children) { | |
| return new RoseTree<>(value, Arrays.asList(children)); | |
| } | |
| public static void main(String[] args) { | |
| RoseTree<Integer> t = rose(1, rose(2), rose(3)); | |
| System.out.println(t.countLeaves()); | |
| System.out.println(t.count()); | |
| System.out.println(t.height()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment