【问题标题】:What is the standard binary search tree structure to use in Scala?Scala 中使用的标准二叉搜索树结构是什么?
【发布时间】:2014-03-26 12:47:11
【问题描述】:

在 Scala 2.10.x 中应该使用的标准平衡二叉搜索树实现是什么?我环顾四周,似乎 AVLTree 已被删除,RedBlack 已被弃用,并带有一条消息 (Since version 2.10.0) use TreeMap or TreeSet instead。但是,TreeMapTreeSet 并没有提供我需要的功能,因为我需要能够遍历树并基于此构建更复杂的数据结构。

是否有任何新类提供未弃用的普通平衡二叉树功能?

【问题讨论】:

标签: scala binary-search-tree avl-tree red-black-tree


【解决方案1】:

树是函数式编程和 Scala 的基础,根据您需求的复杂性,使用适合的任何链接类型和遍历方法滚动您自己的 BTree 并不是一个坏主意。

作为一个通用模型,它可能看起来像这样:

trait BSTree[+A] {
  def value: Option[A] = this match {
    case n: Node[A] => Some(n.v)
    case l: Leaf[A] => Some(l.v)
    case Empty      => None
  }

  def left: Option[BSTree[A]] = this match {
    case n: Node[A] => Some(n.l)
    case l: Leaf[A] => None
    case Empty      => None
  }

  def right: Option[BSTree[A]] = this match {
    case n: Node[A] => Some(n.r)
    case l: Leaf[A] => None
    case Empty      => None
  }
}

case class Node[A](v: A, l: BSTree[A], r: BSTree[A]) extends BSTree[A]
case class Leaf[A](v: A) extends BSTree[A]
case object Empty extends BSTree[Nothing]

【讨论】:

    【解决方案2】:

    你可以试试这个自制的二叉搜索树:

    https://github.com/melvic-ybanez/scala-bst

    就我而言,我正在使用 HashSet,当它们不可变时,它可以非常有效地通过键对数据进行排序。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多