我正在尝试一个编码练习,任务是从二叉搜索树中删除一个节点。这是我目前所拥有的:
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呢?我以为在case class的BranchNode定义中将right和var声明为case classs会允许我对其进行更改吗?
发布于 2017-02-24 09:52:20
您不能改变case class,因为case类背后的思想是保存不可变的数据。
但您可以做的是将数据复制到较新的数据中,并更改您想要的值。
val leftNode = Option(LeafNode(2))
val rightNode = Option(LeafNode(3))
val root = BranchNode(1, leftNode, rightNode)
//i'm deleting or Nonefying the right node in following example
val newRoot = root.copy(right = None) //only overriding the right node
assert(newRoot.label == 1)
assert(newRoot.left == leftNode)
assert(newRoot.right == None)https://stackoverflow.com/questions/42429346
复制相似问题