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

thecoldwine's solution

to Binary Search Tree in the Elixir Track

Published at Feb 10 2021 · 0 comments
Instructions
Test suite
Solution

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:

  4
 /
2

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

  4
 / \
2   6

If we then added 3, it would look like this

   4
 /   \
2     6
 \
  3

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

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

Running tests

Execute the tests with:

$ mix test

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

Source

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.

binary_search_tree_test.exs

defmodule BinarySearchTreeTest do
  use ExUnit.Case

  test "data is retained" do
    assert BinarySearchTree.new(4).data == 4
  end

  describe "insert data at proper node" do
    @tag :pending
    test "smaller number at left node" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(2)

      assert root.data == 4
      assert root.left.data == 2
    end

    @tag :pending
    test "same number at left node" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(4)

      assert root.data == 4
      assert root.left.data == 4
    end

    @tag :pending
    test "greater number at right node" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(5)

      assert root.data == 4
      assert root.right.data == 5
    end
  end

  @tag :pending
  test "can create complex tree" do
    root =
      BinarySearchTree.new(4)
      |> BinarySearchTree.insert(2)
      |> BinarySearchTree.insert(6)
      |> BinarySearchTree.insert(1)
      |> BinarySearchTree.insert(3)
      |> BinarySearchTree.insert(5)
      |> BinarySearchTree.insert(7)

    assert root.data == 4
    assert root.left.data == 2
    assert root.left.left.data == 1
    assert root.left.right.data == 3
    assert root.right.data == 6
    assert root.right.left.data == 5
    assert root.right.right.data == 7
  end

  describe "can sort data" do
    @tag :pending
    test "can sort single number" do
      root = BinarySearchTree.new(4)

      assert [4] == BinarySearchTree.in_order(root)
    end

    @tag :pending
    test "can sort if second number is smaller than first" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(2)

      assert [2, 4] == BinarySearchTree.in_order(root)
    end

    @tag :pending
    test "can sort if second number is the same as the first" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(4)

      assert [4, 4] == BinarySearchTree.in_order(root)
    end

    @tag :pending
    test "can sort if second number is greater than the first" do
      root =
        BinarySearchTree.new(4)
        |> BinarySearchTree.insert(5)

      assert [4, 5] == BinarySearchTree.in_order(root)
    end

    @tag :pending
    test "can sort complex tree" do
      root =
        BinarySearchTree.new(2)
        |> BinarySearchTree.insert(1)
        |> BinarySearchTree.insert(3)
        |> BinarySearchTree.insert(6)
        |> BinarySearchTree.insert(7)
        |> BinarySearchTree.insert(5)

      assert [1, 2, 3, 5, 6, 7] == BinarySearchTree.in_order(root)
    end
  end
end

test_helper.exs

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule BinarySearchTree do
  @type bst_node :: %{data: any, left: bst_node | nil, right: bst_node | nil}

  @doc """
  Create a new Binary Search Tree with root's value as the given 'data'
  """
  @spec new(any) :: bst_node
  def new(data) do
    %{data: data, left: nil, right: nil}
  end

  @doc """
  Creates and inserts a node with its value as 'data' into the tree.
  """
  @spec insert(bst_node, any) :: bst_node
  def insert(nil, data), do: new(data)
  def insert(%{data: d, left: l, right: r} = tree, data) do
    cond do
      data > d -> %{tree | right: insert(r, data)}
      true -> %{tree | left: insert(l, data)}
    end
  end

  @doc """
  Traverses the Binary Search Tree in order and returns a list of each node's data.
  """
  @spec in_order(bst_node) :: [any]
  def in_order(nil), do: []
  def in_order(%{data: d, left: l, right: r}), do: in_order(l) ++ [d] ++ in_order(r)

end

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?