Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the standard binary search tree structure to use in Scala?

What is the standard balanced binary search tree implementation one should use in Scala 2.10.x? I am looking around and it seems that AVLTree was removed and RedBlack is deprecated with a message (Since version 2.10.0) use TreeMap or TreeSet instead. However, TreeMap and TreeSet do not provide the functionality I need because I need to be able to traverse the tree and build a more complex data structure based on this.

Is there any new class that provides the plain balanced binary tree functionality that is not deprecated?

like image 951
jbx Avatar asked Feb 24 '14 17:02

jbx


People also ask

Which data structure is used for binary search tree?

A BST is considered a data structure made up of nodes, like Linked Lists. These nodes are either null or have references (links) to other nodes. These 'other' nodes are child nodes, called a left node and right node. Nodes have values.

What is binary search tree explain with example?

Binary search tree is a data structure that quickly allows us to maintain a sorted list of numbers. It is called a binary tree because each tree node has a maximum of two children. It is called a search tree because it can be used to search for the presence of a number in O(log(n)) time.

What is tree search in data structure?

In computer science, a search tree is a tree data structure used for locating specific keys from within a set. In order for a tree to function as a search tree, the key for each node must be greater than any keys in subtrees on the left, and less than any keys in subtrees on the right.


2 Answers

Trees are fundamental to functional programming and scala, and depending on the complexity of your requirement it wouldn't be a bad idea to roll your own BTree with whatever linkage type and traversal methods fit.

As a general model it could look something like this:

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]
like image 136
Alex Ehrnschwender Avatar answered Nov 05 '22 22:11

Alex Ehrnschwender


You can try this home-made version of binary search trees:

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

As far as I'm concerned, I am using HashSet which sort the data by key very efficiently when they are immutable.

like image 42
Mikaël Mayer Avatar answered Nov 05 '22 21:11

Mikaël Mayer