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