ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# moreirarodrigo's solution

## to Binary Search Tree in the Elixir Track

Published at Mar 20 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.

## 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}

@doc """
Creates and inserts a node with its value as 'data' into the tree.
"""
@spec insert(bst_node, any) :: bst_node
def insert(tree, data) do
cond do
tree == nil -> new(data)
tree.data >= data -> %{tree | left: insert(tree.left, data)}
tree.data < data -> %{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
case is_nil(tree) do
true -> []
_ -> in_order(tree.left) ++ [tree.data] ++ in_order(tree.right)
end
end
end``````