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?
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.
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.
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With