Guest User

Untitled

a guest
Feb 19th, 2021
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.70 KB | None | 0 0
  1. fun main() {
  2.     val tree = Node(
  3.         1,
  4.         listOf(
  5.             Node(
  6.                 2, listOf(
  7.                     Node(3),
  8.                     Node(4),
  9.                     Node(5)
  10.                 )
  11.             ),
  12.             Node(6)
  13.         )
  14.     )
  15.  
  16.     val list = preorder({ x -> print("$x ") }, tree) //.map { it.rootLabel }
  17.     println()
  18.     println(list)
  19. }
  20.  
  21. fun preorder(transform: (Int) -> Unit, node: Node) : List<Node>{
  22.     val els: () -> List<Node> = { node.subForest.flatMap { preorder(transform, it) }}
  23.     transform(node.rootLabel)
  24.     return listOf(node) + els.invoke()
  25. }
  26.  
  27. data class Node(
  28.     val rootLabel: Int,
  29.     val subForest: List<Node> = emptyList()
  30. )
Advertisement
Add Comment
Please, Sign In to add comment