Home > Mobile >  Depth of a binary Tree in Kotlin
Depth of a binary Tree in Kotlin

Time:06-06

I'm trying to write code to find the depth of a binary tree.

I know that it need to be rekursiv,thank you very much in advance for your answer.

Here is my Code in Kotlin.

    sealed class Tree <A>{

    abstract fun isEmpty() : Boolean
    abstract fun size() : Int
    abstract fun depth() : Int

}

private data class Node <A >(
    val value : A,
    val left : Tree <A>,
    val right : Tree <A>
) : Tree <A >() {
    override fun isEmpty(): Boolean = false

    override fun size(): Int = 1   left.size()   right.size()

    override fun depth(): Int {

         if (!left.isEmpty()) // I tried to work with isEmpty()

    }
}

private object Empty : Tree < Nothing >() {
    override fun isEmpty(): Boolean = true
    override fun size(): Int = 0
    override fun depth(): Int = 0
}

fun <A> emptyTree () : Tree <A> = Empty as Tree <A>
fun <A> treeNode (
    value : A,
    left : Tree <A> = emptyTree () ,
    right : Tree <A> = emptyTree ()
): Tree <A> = Node (value , left , right )


fun main(){

    var tree : Tree<Int> = emptyTree()

    tree = treeNode(5,treeNode(3,treeNode(2,treeNode(1)),treeNode(4)),treeNode(8,emptyTree(),treeNode(10)));

I tested my Code with a Tree with 7 Nodes

    println(tree.size())
    println(tree.depth())
}

CodePudding user response:

Try to do it in the same way as size: the depth of a node is 1 plus the largest of left.depth() and right.depth().

  • Related