Avatar of davearonson

davearonson's solution

to Binary Search Tree in the Elixir Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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:

$ elixir binary_search_tree_test.exs

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

For more detailed information about the Elixir track, please see the help page.

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

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("binary_search_tree.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule BinarySearchTreeTest do
  use ExUnit.Case

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

  @tag :pending
  test "inserting lower number" do
    root =
      BinarySearchTree.new(4)
      |> BinarySearchTree.insert(2)

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

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

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

  @tag :pending
  test "inserting higher number" do
    root =
      BinarySearchTree.new(4)
      |> BinarySearchTree.insert(5)

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

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

    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

  @tag :pending
  test "iterating one element" do
    root = BinarySearchTree.new(4)

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

  @tag :pending
  test "iterating over smaller element" do
    root =
      BinarySearchTree.new(4)
      |> BinarySearchTree.insert(2)

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

  @tag :pending
  test "iterating over larger element" do
    root =
      BinarySearchTree.new(4)
      |> BinarySearchTree.insert(5)

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

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

    assert [1, 2, 3, 4, 5, 6, 7] == BinarySearchTree.in_order(root)
  end
end
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(tree, data)  do
    if data <= tree.data do
      %{tree | left: insert(tree.left, data) }
    else
      %{tree | right: insert(tree.right, 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(tree) do
    # could do "in_order(tree.left) ++ [tree.data|in_order(tree.right)]",
    # (with in_order(nil) as []), but ++ is very inefficient.  this way is
    # sorta cheating, because it does not really *traverse* in order, but
    # does *return* the data in order.
    do_in_order(tree, [])
  end

  defp do_in_order(nil , acc), do: acc
  defp do_in_order(tree, acc)  do
    do_in_order(tree.left, [tree.data|do_in_order(tree.right, acc)])
  end

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?