首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选项成员的Setters

选项成员的Setters
EN

Stack Overflow用户
提问于 2017-02-24 09:43:31
回答 1查看 47关注 0票数 0

我正在尝试一个编码练习,任务是从二叉搜索树中删除一个节点。这是我目前所拥有的:

代码语言:javascript
复制
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呢?我以为在case classBranchNode定义中将rightvar声明为case classs会允许我对其进行更改吗?

EN

回答 1

Stack Overflow用户

发布于 2017-02-24 09:52:20

您不能改变case class,因为case类背后的思想是保存不可变的数据。

但您可以做的是将数据复制到较新的数据中,并更改您想要的值。

代码语言:javascript
复制
  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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42429346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档