2017-02-24 4 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의 left 또는 right 노드를 None으로 설정하는 방법은 무엇입니까? 나는 과 right을 정의 vars로 정의하고 BranchNode이라고 정의하면 그것을 돌연변이시킬 수 있다고 생각 했는가?

답변

1

케이스 클래스 뒤에있는 아이디어가 변경 불가능한 데이터를 보유하기 때문에 case class을 변경할 수 없습니다.

하지만 할 수있는 것은 데이터를 새로운 것으로 복사하고 원하는 값을 변경하는 것입니다.

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'의 타입이'BranchNode' 대신에'Option [Node]'라면 어떻게 복사합니까? 우리는 세 가지 가능성과 복사를 모두 가진 '루트'패턴을 따라 가야합니까? – shaktimaan