Home > Enterprise >  Using recursion to get the sum of a tree, but the root node won't add in Kotlin
Using recursion to get the sum of a tree, but the root node won't add in Kotlin

Time:09-05

I'm doing a question to get the sum of an entire tree through recursion, but the root node wont add with the child node. Now I'm aware that the root node is just a value while the child nodes are Tree nodes, so there not the same type.

class TreeNode<T>(var key: T){
    var left: TreeNode<T>? = null
    var right: TreeNode<T>? = null
}



fun treeSumR(root: TreeNode<Int>): Int{
    if (root == null) return 0
    return root.key   root.left?.let { treeSumR(it) }   root.right?.let { treeSumR(it) }
}



fun buildTree2(): TreeNode<Int>{
    val one = TreeNode(1)
    val two = TreeNode(2)
    val four = TreeNode(4)
    val eleven = TreeNode(11)
    val three = TreeNode(3)
    val four2 = TreeNode(4)

    three.left = eleven
    three.right = four
    eleven.left = four2
    eleven.right = two
    four.right = one

    return three

}

Any help is appreciated. Thanks.

CodePudding user response:

There is an error on the operators because you are adding a non-nullable Int (root.key) and nullable Int?s (the sums of the subtrees) together. The sums of the subtrees are nullable because you wrote ?.. Its effect is that the whole expression of root.left?.let { ... } evaluates to null if root.left is null.

You can provide a default value for the expression when it is null by using the elvis operator:

return root.key  
    (root.left?.let { treeSumR(it) } ?: 0)  
    (root.right?.let { treeSumR(it) } ?: 0)

However, since you are already checking if root is null and returning 0, a better way is to make root actually nullable, and pass root.left and root.right directly into it treeSumR:

//               notice the question mark here
//                              v
fun treeSumR(root: TreeNode<Int>?): Int{
    if (root == null) return 0
    return root.key  
        treeSumR(root.left)   // since treeSumR now takes a nullable node, you can directly pass the subtrees in
        treeSumR(root.right)
}
  • Related