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
을 정의 var
s로 정의하고 BranchNode
이라고 정의하면 그것을 돌연변이시킬 수 있다고 생각 했는가?
고맙습니다. 'root'의 타입이'BranchNode' 대신에'Option [Node]'라면 어떻게 복사합니까? 우리는 세 가지 가능성과 복사를 모두 가진 '루트'패턴을 따라 가야합니까? – shaktimaan