如何为此Btree实现实现“查找”方法

时间:2018-08-24 05:13:13

标签: scala b-tree

因此我正在学习Scala。这是所有Nodes和BTree的基类

abstract sealed class Node[T](implicit val ord : Ordering[T])

abstract sealed class BTree[T](implicit ord : Ordering[T])
extends Node[T] {
def size : Int
def depth : Int

这是基本案例的结尾

object BTree {
//empty node
final case class EmptyNode[T]()(implicit ord : Ordering[T])
  extends BTree[T] {
val size : Int = 0
val depth : Int = 0
}
//node with 1 child
final case class OneNode[T](t : BTree[T])(implicit ord : Ordering[T])
  extends Node[T] {
val size : Int = t.size
val depth : Int = t.depth + 1
}
//node with 2 children
final case class TwoNode[T](t1 : BTree[T], u1 : T, t2 : BTree[T])
                      (implicit ord : Ordering[T]) extends BTree[T] {
val size : Int = t1.size + t2.size + 1
val depth : Int = max(t1.depth, t2.depth) + 1
}

然后他们继续使用ThreeNodeFourNode的模式

现在在BTree类中,我必须实现一个find函数

//return `Some` of entry if equivalent is found, None if not. 
def find(v : T) : Option[T] = 

而且我无法将我的头围在我需要做的事情上。在Java中,我只会做一个遍历每个节点或任何节点的循环,但是Scala我不知道。甚至Some东西。回报只是Some(v)吗?无论如何,这就是我能想到的

//return `Some` of entry if equivalent is found, None if not. 
def find(v : T) : Option[T] = 
this match {

  case EmptyNode() => None

  case TwoNode(EmptyNode(), u1, EmptyNode()) if (v equiv u1) =>
    Some(v)

  case TwoNode(t1, u1, t2) if (v equiv u1) =>
    Some(v)

在这些情况下我该怎么办:

  case TwoNode(t1, u1, t2) if (v < u1) => 

  case TwoNode(t1, u1, t2) if (u1 < v) => 

条目可能在树的更下方。

ThreeNode我也有类似情况

  case ThreeNode(EmptyNode(), u1, EmptyNode(), u2, EmptyNode()) if (v equiv u1) =>
    Some(v)
  case ThreeNode(EmptyNode(), u1, EmptyNode(), u2, EmptyNode()) if (v equiv u2) =>
    Some(v)

  case ThreeNode(t1, u1, t2, u2, t3) if (v equiv u1) =>
    Some(v)
  case ThreeNode(t1, u1, t2, u2, t3) if (v equiv u2) =>
    Some(v)

但是,再次重申,如果v在树的下方,该怎么办。

   case ThreeNode(t1, u1, t2, u2, t3) if (v < u1) =>

   case ThreeNode(t1, u1, t2, u2, t3) if (u1 < v  && v < u2) =>

   case ThreeNode(t1, u1, t2, u2, t3) if (u2 < v) =>

我也不确定发现Some(v)是否正确。

任何帮助表示赞赏。谢谢

1 个答案:

答案 0 :(得分:1)

您需要使用递归find方法,如下所示:

  def find(v: T): Boolean =
    this match {
      case OneNode(t1, u1) =>
        (u1 == v) || t1.find(v)
      case TwoNode(t1, u1, t2) =>
        (u1 == v) || t1.find(v) || t2.find(v)
      case _ => false
    }

此版本返回Boolean,因为该值存在或不存在。如果要返回值所在的节点,则需要返回Option[BTree[T]],逻辑会变得更加复杂:

  def findNode(v: T): Option[BTree[T]] =
    this match {
      case OneNode(t1, u1) =>
        if (u1 == v) {
          Some(this)
        } else {
          t1.findNode(v)
        }
      case TwoNode(t1, u1, t2) =>
        if (u1 == v) {
          Some(this)
        } else {
          t1.findNode(v) orElse t2.findNode(v)
        }
      case _ => None
    }

对于4个节点,这将变得很笨拙,因此我建议您使用List[BTree[T]]而不是枚举子节点。这将使代码更加清晰。

还请注意,您需要向u1添加一个OneNode成员,并且该成员应该继承自BTree[T]而不是Node[T],否则您将无法添加它到其他节点。