Published at Aug 26 2019
·
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
```

Execute the tests with:

```
$ mix test
```

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.

Josh Cheek https://twitter.com/josh_cheek

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

```
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
```

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

```
defmodule BinarySearchTree do
@type bst_node :: %{data: any, left: bst_node | nil, right: bst_node | nil}
defguardp left_node?(node_value, data) when data <= node_value
@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(%{data: node_value, left: nil} = tree, data)
when left_node?(node_value, data) do
%{tree | left: new(data)}
end
def insert(%{data: node_value, left: left_node} = tree, data)
when left_node?(node_value, data) do
%{tree | left: insert(left_node, data)}
end
def insert(%{right: nil} = tree, data), do: %{tree | right: new(data)}
def insert(%{right: right_node} = tree, data) do
%{tree | right: insert(right_node, data)}
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
tree
|> in_order([])
|> Enum.reverse()
end
defp in_order(nil, acc), do: acc
defp in_order(%{data: data, left: nil, right: nil}, acc), do: [data | acc]
defp in_order(%{data: data, left: left, right: right}, acc) do
ordered_left = [data | in_order(left, acc)]
in_order(right, ordered_left)
end
end
```

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?

Level up your programming skills with 3,285 exercises across 51 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments