2017-02-24 40 views
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的leftright节点设置为None?我认为leftrightvar s在case class定义为BranchNode会允许我改变吗?

回答

1

您不能改变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) 
+0

谢谢。如果'root'的类型是'Option [Node]'而不是'BranchNode',你将如何复制?我们是否需要通过匹配具有所有三种可能性的“root”模式并进行复制? – shaktimaan

相关问题