Advertisement
fogone

tree

Jul 15th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.50 KB | None | 0 0
  1. data class Node<T>(val value: T, var left: Node<T>? = null, var right: Node<T>? = null)
  2.  
  3. private fun <T> Node<T>.visit(action: (T) -> Unit) {
  4.     left?.run { visit(action) }
  5.  
  6.     action(value)
  7.  
  8.     right?.run { visit(action) }
  9. }
  10.  
  11.  
  12. interface TreeStrategy<T> {
  13.  
  14.     fun add(parent: Node<T>?, node: Node<T>): Node<T>
  15.  
  16. }
  17.  
  18. class SimpleComparatorTreeStrategy<T>(val comparator: Comparator<T>) : TreeStrategy<T> {
  19.  
  20.     override fun add(parent: Node<T>?, node: Node<T>):Node<T> {
  21.         if (parent == null) {
  22.             return node
  23.         }
  24.  
  25.         val compareResult = comparator.compare(parent.value, node.value)
  26.  
  27.         when {
  28.             compareResult.lessThanParent -> parent.left = add(parent.left, node)
  29.             compareResult.moreThanParent -> parent.right = add(parent.right, node)
  30.         }
  31.  
  32.         return parent
  33.     }
  34.  
  35.     private val Int.moreThanParent: Boolean get() = this < 0
  36.     private val Int.lessThanParent: Boolean get() = this >= 0
  37.  
  38. }
  39.  
  40. class Tree<T>(val strategy: TreeStrategy<T>) {
  41.  
  42.     private var root: Node<T>? = null
  43.  
  44.     fun add(value: T) {
  45.         this.root = strategy.add(this.root, Node(value))
  46.     }
  47.  
  48.     fun forEach(action: (T) -> Unit) {
  49.         root?.run { visit(action) }
  50.     }
  51.  
  52. }
  53.  
  54. fun <T : Comparable<T>> treeOf(vararg values: T): Tree<T> = Tree<T>(SimpleComparatorTreeStrategy(compareBy { it }))
  55.         .also { tree -> values.forEach(tree::add) }
  56.  
  57. fun main(args: Array<String>) {
  58.     treeOf("test1", "test2", "t", "abcd").forEach(::println)
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement