Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data class Node<T>(val value: T, var left: Node<T>? = null, var right: Node<T>? = null)
- private fun <T> Node<T>.visit(action: (T) -> Unit) {
- left?.run { visit(action) }
- action(value)
- right?.run { visit(action) }
- }
- interface TreeStrategy<T> {
- fun add(parent: Node<T>?, node: Node<T>): Node<T>
- }
- class SimpleComparatorTreeStrategy<T>(val comparator: Comparator<T>) : TreeStrategy<T> {
- override fun add(parent: Node<T>?, node: Node<T>):Node<T> {
- if (parent == null) {
- return node
- }
- val compareResult = comparator.compare(parent.value, node.value)
- when {
- compareResult.lessThanParent -> parent.left = add(parent.left, node)
- compareResult.moreThanParent -> parent.right = add(parent.right, node)
- }
- return parent
- }
- private val Int.moreThanParent: Boolean get() = this < 0
- private val Int.lessThanParent: Boolean get() = this >= 0
- }
- class Tree<T>(val strategy: TreeStrategy<T>) {
- private var root: Node<T>? = null
- fun add(value: T) {
- this.root = strategy.add(this.root, Node(value))
- }
- fun forEach(action: (T) -> Unit) {
- root?.run { visit(action) }
- }
- }
- fun <T : Comparable<T>> treeOf(vararg values: T): Tree<T> = Tree<T>(SimpleComparatorTreeStrategy(compareBy { it }))
- .also { tree -> values.forEach(tree::add) }
- fun main(args: Array<String>) {
- treeOf("test1", "test2", "t", "abcd").forEach(::println)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement