【问题标题】:Using DFS to print out a Tree in Kotlin在 Kotlin 中使用 DFS 打印一棵树
【发布时间】:2022-11-11 05:12:34
【问题描述】:

我正在研究 Trees 并想在 Stack 中打印出树

这是我到目前为止所得到的。

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

fun depthFirstValues(root: TreeNode<Char>){
    val stack = mutableListOf(root)
    while (stack.size > 0){
       val current = stack.removeFirst()
//        println(current.key)

        if(current.right!!.equals(true)) stack.add(current.right!!)
        if (current.left!!.equals(true)) stack.add(current.left!!)


    }
    println(stack)
}

fun buildTree(): TreeNode<Char>{
    val a = TreeNode('a')
    val b = TreeNode('b')
    val c = TreeNode('c')
    val d = TreeNode('d')
    val e = TreeNode('e')
    val f = TreeNode('f')


    a.left = b
    a.right = c
    b.left = d
    b.right = e
    c.right = f

    return a
}

我得到一个 emptyList 作为返回值。我整天都在修补它,但不知道如何让它工作。任何帮助将不胜感激。谢谢你。

【问题讨论】:

    标签: algorithm kotlin binary-tree


    【解决方案1】:

    我发现您的代码存在三个主要问题。

    • 如果要将整个遍历存储在一个集合中,并在最后打印出来,则需要一个额外的集合来存储深度优先遍历的结果。

      您不能只使用与用于实现遍历的堆栈相同的堆栈,因为该堆栈是保证在算法结束时为空,如 while 循环上的条件所示 - stack.size == 0

    • 您实际上并没有像堆栈一样使用stack。您正在从其前面删除元素 (removeFirst),但添加到其末尾 (add),就像一个队列。要像堆栈一样使用它,您应该添加到/从中删除相同的列表的末尾。

    • 您没有正确检查空值。如果current.right 不为空,current.right!!.equals(true) 为假,如果为空,则将引发异常 - 根本没有多大意义,不是吗?

    解决这些问题,我们有:

    fun depthFirstValues(root: TreeNode<Char>){
        val stack = mutableListOf(root)
        val result = mutableListOf<Char>()
        while (stack.isNotEmpty()){
            val current = stack.removeLast()
            current.left?.apply(stack::add)
            current.right?.apply(stack::add)
            result.add(current.key) // could also get rid of "result" and just println(current.key) here
        }
        println(result)
    }
    

    当应用于您的树时,它会打印[a, c, f, b, e, d]

    【讨论】:

    • 谢谢你。我绝对错误地解释了这个问题。我整天都在电脑上,完全错过了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多