【问题标题】:Functional Programming in Kotlin, Manning book - binary tree structureKotlin 中的函数式编程,Manning 书 - 二叉树结构
【发布时间】:2021-08-01 23:07:52
【问题描述】:

我一直在完成本书中的练习。写的很好,但是速度很快。到目前为止,我一直在跟上。

但是,我对二叉树的经验为零,我被困在这棵树上。这是作业:

编写一个函数 size 来计算树中节点(叶子和分支)的数量。

这是一个密封类的树结构:

sealed class Tree<out A>
data class Leaf<A>(var value: A) : Tree<A>()
data class Branch<A>(val left: Tree<A>, val right: Tree<A>) : Tree<A>()

我不得不搜索有关二叉树的信息,并在 Kotlin 中找到了一个我可以理解的示例。

但该样本具有三态结构,而练习具有双态:

class BinaryNode<Element>(
    val value: Element,
    var leftChild: BinaryNode<Element>? = null,
    var rightChild: BinaryNode<Element>? = null
) {

所以,我在使用密封类构建有效二叉树时遇到了麻烦,我可以在上面测试练习解决方案,即:

fun <A> size(tree: Tree<A>): Int =
    when (tree) {
        is Leaf -> 1
        is Branch -> 1 + size(tree.left) + size(tree.right)
    }

解决方案看起来很合理,但不能完全弄清楚树的构造。

任何帮助将不胜感激。

【问题讨论】:

    标签: kotlin functional-programming tree binary-tree


    【解决方案1】:

    这是一个简单的例子:

    fun main() {
        val tree = Branch(
            Branch(
                Leaf(1),
                Leaf(2)
            ),
            Branch(
                Leaf(3),
                Branch(
                    Leaf(4),
                    Leaf(5)
                )
            )
        )
        println(size(tree))
    }
    

    这会打印出9,即 5 片叶子加上树枝。

    【讨论】:

    • 啊,嵌套分支。类似于书中嵌套的 Cons 列表结构。谢谢。
    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多