fork download
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;
  5. import java.util.Objects;
  6. import java.util.stream.Collectors;
  7.  
  8. class Scratch {
  9.  
  10. public static void main(String[] args) {
  11. Node<Integer> root = new Node<>(8, List.of(
  12. new Node<>(4, List.of(
  13. new Node<>(1),
  14. new Node<>(4),
  15. new Node<>(3))),
  16. new Node<>(3, List.of(
  17. new Node<>(3),
  18. new Node<>(5),
  19. new Node<>(6),
  20. new Node<>(4))),
  21. new Node<>(7, List.of(
  22. new Node<>(12),
  23. new Node<>(32),
  24. new Node<>(3),
  25. new Node<>(1)))));
  26. System.out.println(getMaxValuePerLevel(root));
  27. }
  28.  
  29. public static <T extends Comparable<T>> List<T> getMaxValuePerLevel(Node<T> node) {
  30. final ArrayList<T> maxPerLevel = new ArrayList<>();
  31. maxPerLevel.add(node.getValue());
  32. List<Node<T>> children = node.getChildren();
  33. while (!children.isEmpty()) {
  34. final Node<T> defaultNode = children.get(0);
  35. maxPerLevel.add(children.stream()
  36. .map(Node::getValue)
  37. .max(Comparator.naturalOrder())
  38. .orElseGet(defaultNode::getValue));
  39. children = children.stream()
  40. .map(Node::getChildren)
  41. .flatMap(List::stream)
  42. .collect(Collectors.toList());
  43. }
  44. return maxPerLevel;
  45. }
  46. }
  47.  
  48. class Node<T extends Comparable<T>> {
  49. private final T value;
  50. private final List<Node<T>> children;
  51.  
  52. public Node(T value) {
  53. this(value, Collections.emptyList());
  54. }
  55.  
  56. public Node(T value, List<Node<T>> children) {
  57. this.value = Objects.requireNonNull(value);
  58. this.children = Objects.requireNonNull(children).stream()
  59. .filter(Objects::nonNull)
  60. .collect(Collectors.toUnmodifiableList());
  61. }
  62.  
  63. public T getValue() {
  64. return value;
  65. }
  66.  
  67. public List<Node<T>> getChildren() {
  68. return children;
  69. }
  70. }
Success #stdin #stdout 0.08s 34312KB
stdin
Standard input is empty
stdout
[8, 7, 32]