🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of SergiiVlasiuk

SergiiVlasiuk's solution

to Binary Search Tree in the Scala Track

Published at Aug 26 2019 · 0 comments
Test suite

Insert and search for numbers in a binary tree.

When we need to represent sorted data, an array does not make a good data structure.

Say we have the array [1, 3, 4, 5], and we add 2 to it so it becomes [1, 3, 4, 5, 2] now we must sort the entire array again! We can improve on this by realizing that we only need to make space for the new item [1, nil, 3, 4, 5], and then adding the item in the space we added. But this still requires us to shift many elements down by one.

Binary Search Trees, however, can operate on sorted data much more efficiently.

A binary search tree consists of a series of connected nodes. Each node contains a piece of data (e.g. the number 3), a variable named left, and a variable named right. The left and right variables point at nil, or other nodes. Since these other nodes in turn have other nodes beneath them, we say that the left and right variables are pointing at subtrees. All data in the left subtree is less than or equal to the current node's data, and all data in the right subtree is greater than the current node's data.

For example, if we had a node containing the data 4, and we added the data 2, our tree would look like this:


If we then added 6, it would look like this:

 / \
2   6

If we then added 3, it would look like this

 /   \
2     6

And if we then added 1, 5, and 7, it would look like this

    /   \
   /     \
  2       6
 / \     / \
1   3   5   7

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

For more detailed info about the Scala track see the help page.


Josh Cheek https://twitter.com/josh_cheek

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import org.scalatest.{Matchers, FlatSpec}

/** @version created manually **/
class BstTest extends FlatSpec with Matchers {
  val bst4 = Bst(4)

  it should "retain data" in {
    bst4.value should equal(4)

  it should "retain data - char" in {
    Bst('d').value should equal('d')

  it should "insert less" in {
    bst4.insert(2).left.get.value should equal(2)

  it should "insert less - char" in {
    Bst('d').insert('a').left.get.value should equal('a')

  it should "insert same" in {
    bst4.insert(4).left.get.value should equal(4)

  it should "insert greater than" in {
    bst4.insert(5).right.get.value should equal(5)

  it should "handle complex tree - sort out of order list" in {
    val bst = Bst.fromList(List(4, 2, 6, 1, 3, 7, 5))
    Bst.toList(bst) should equal((1 to 7).toList)

    bst.value should equal(4)
    bst.left.get.value should equal(2)
    bst.left.get.left.get.value should equal(1)
    bst.left.get.right.get.value should equal(3)
    bst.right.get.value should equal(6)
    bst.right.get.left.get.value should equal(5)
    bst.right.get.right.get.value should equal(7)

  it should "iterating one element" in {
    Bst.toList(bst4) should equal(List(4))

  it should "iterating over smaller element" in {
    Bst.toList(Bst.fromList(List(4, 2))) should equal(List(2, 4))

  it should "iterating over larger element" in {
    Bst.toList(Bst.fromList(List(4, 5))) should equal(List(4, 5))

  it should "iterating over complex tree" in {
    Bst.toList(Bst.fromList(List(4, 2, 1, 3, 6, 7, 5))) should equal((1 to 7).toList)

  it should "iterating over complex tree - chars" in {
    Bst.toList(Bst.fromList(List('d', 'b', 'a', 'c', 'f', 'g', 'e'))) should
      equal(('a' to 'g').toList)
object Bst {
  def fromList(l: List[Int]): Bst = l match {
    case Nil => throw new IllegalArgumentException("At least 1 item in the list is required")
    case x :: xs => xs.foldLeft(Bst(x))((agg, x) => agg.insert(x))

  def toList(bst: Bst): List[Int] = bst match {
    case Bst(v, Some(left), Some(right)) => toList(left) ++ (v :: toList(right))
    case Bst(v, None, Some(right)) => v :: toList(right)
    case Bst(v, Some(left), None) => toList(left) ++ (v :: Nil)
    case Bst(v, None, None) => v :: Nil

case class Bst(value: Int, left: Option[Bst] = None, right: Option[Bst] = None) {
  def insert(item: Int): Bst = if (item <= value) { // to left
    val newLeft = if (left == None) Bst(item) else left.get.insert(item)
    Bst(value, Some(newLeft), right)
  } else { //to right
    val newRight = if (right == None) Bst(item) else right.get.insert(item)
    Bst(value, left, Some(newRight))

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?