Below are the classic binary tree recursive traversal methods embedded into our BinaryNode class. We use a companion object to minimize our space complexity, which is comparable to static methods in Java. You may wonder why we allow for a nullable _BinaryNode _to be passed into each of these methods. I settled at this option for the sake of clarity. Because the left and right nodes are mutable objects, we would need to create immutable references to them before passing them to the recursive calls. You could say our base case is an empty leaf node.

The wonderful part about Kotlin is that we can define our action as a lambda expression. Below you will see an action defined as a parameter, which uses the value of the node being passed in as the first parameter. Our action here returns Unit, which is comparable to returning void in Java. Let’s look at how we can use this lambda expression.

class BinaryNode<T>(
    var value: T,
    var left: BinaryNode<T>? = null,
    var right: BinaryNode<T>? = null
) {

    companion object {

        fun <T> traversePreorder(
            node: BinaryNode<T>?,
            action: (value: T) -> Unit
        ) {
            if(node != null) {
                action.invoke(node.value)
                traversePreorder(node.left, action)
                traversePreorder(node.right, action)
            }
        }

        fun <T> traverseInorder(
            node: BinaryNode<T>?,
            action: (value: T) -> Unit
        ) {
            if(node != null) {
                traverseInorder(node.left, action)
                action.invoke(node.value)
                traverseInorder(node.right, action)
            }
        }

        fun <T> traversePostOrder(
            node: BinaryNode<T>?,
            action: (value: T) -> Unit
        ) {
            if (node != null) {
                traversePostOrder(node.left, action)
                traversePostOrder(node.right, action)
                action.invoke(node.value)
            }
        }
    }
}

#preorder-traversal #n-ary-tree #kotlin #binary-tree #depth-first

Tree Traversals in Kotlin
9.05 GEEK