【发布时间】: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