0
我正在尝试编码练习,其任务是从二进制搜索树中删除一个节点。这是我目前的:选项成员的安装程序
sealed trait Node {
val label: Int
}
case class LeafNode(override val label: Int) extends Node
case class BranchNode(override val label: Int, var left: Option[Node], var right: Option[Node]) extends Node
def deleteFromBST(root: Option[Node], valueToDelete: Int): Option[Node] = {
def doTheDelete(node: Option[Node], parent: Option[Node]): Option[Node] = (node, parent) match {
// Handle other possibilities of (node, parent)
...
// Case where the root needs replacement
case (Some(BranchNode(label, left, right)), None) => {
// Root replacement.
// Get the replacement node and it's parent
var (replacement, repParent) = getTheLeastInTheTree(right)
// Mark the previous parent of the replacement node as not having this child anymore
if (repParent.get.label > replacement.get.label) {
repParent // <-- This is where I am stuck
}
...
}
...
}
我已经从上面的代码中删除了其他函数,以保持代码的简洁。现在,在“这是我卡住的地方”,我该如何将repParent的left
或right
节点设置为None
?我认为left
和right
为var
s在case class
定义为BranchNode
会允许我改变吗?
谢谢。如果'root'的类型是'Option [Node]'而不是'BranchNode',你将如何复制?我们是否需要通过匹配具有所有三种可能性的“root”模式并进行复制? – shaktimaan