Skip to content

Commit

Permalink
Binary search tree (#299)
Browse files Browse the repository at this point in the history
* Init solution

* remove root

* Implement

* explain problems with trees in immutable languages like Cairo

* lint code

* Reimplement using Option + Box
  • Loading branch information
0xNeshi authored Nov 10, 2024
1 parent be13943 commit 2f5bd88
Show file tree
Hide file tree
Showing 9 changed files with 356 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,14 @@
"prerequisites": [],
"difficulty": 4
},
{
"slug": "binary-search-tree",
"name": "Binary Search Tree",
"uuid": "97941277-12ff-474b-8a41-e89c065e0620",
"practices": [],
"prerequisites": [],
"difficulty": 6
},
{
"slug": "knapsack",
"name": "Knapsack",
Expand Down
53 changes: 53 additions & 0 deletions exercises/practice/binary-search-tree/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Instructions append

Implementing an efficient and modifiable tree structure in Cairo (or any purely functional language with immutable memory) is challenging because these languages are designed to avoid changing data after it’s created.
This immutability means that instead of updating a tree node directly, a new version of the tree must be created whenever you modify it.

To show why this is the case, imagine a simple binary tree structure where each node has a left and a right child.
Let's say we start with a small tree like this:

```c
1
/ \
2 3
```

Now, suppose we want to add a new node `4` as the left child of node `2`.
In a purely functional language (like in Cairo or Haskell), memory is immutable, so we can’t simply add node `4` directly to `2`.
Instead, we have to create a new version of each node along the path from the root to the modified node, because every node along this path now points to a new or modified subtree.

Here’s what the process would look like:

1. **Add Node 4 to Node 2**:
- Create a new version of node `2`, which now has `4` as its left child.

```c
2'
/
4
```

2. **Update the Root Node**:
- Since node `1` originally pointed to the old `2`, we create a new version of the root node `1'` that now points to the updated node `2'` on the left and keeps node `3` on the right.

```c
1'
/ \
2' 3
```

So, the resulting tree becomes:

```c
1'
/ \
2' 3
/
4
```

This new tree (`1'`) still resembles the original, but with an updated path.
The key point is that we had to re-create each node along the path (`1` to `2`) to preserve immutability, since existing nodes cannot be modified in place.
The original tree still exists (for example, for all references to its original root `1`), while this new tree represents the modified state.

In large trees, this approach can become expensive, as every new modification requires recreating a path of nodes from the root to the updated node, even if only a small part of the tree is actually changed.
47 changes: 47 additions & 0 deletions exercises/practice/binary-search-tree/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Instructions

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
21 changes: 21 additions & 0 deletions exercises/practice/binary-search-tree/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"authors": [
"0xNeshi"
],
"files": {
"solution": [
"src/lib.cairo"
],
"test": [
"tests/binary_search_tree.cairo"
],
"example": [
".meta/example.cairo"
],
"invalidator": [
"Scarb.toml"
]
},
"blurb": "Insert and search for numbers in a binary tree.",
"source": "Josh Cheek"
}
74 changes: 74 additions & 0 deletions exercises/practice/binary-search-tree/.meta/example.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
type BinarySearchTree = Option<Box<Node>>;

#[derive(Drop, Copy)]
struct Node {
value: u32,
left: BinarySearchTree,
right: BinarySearchTree,
}

#[generate_trait]
pub impl BinarySearchTreeImpl of BinarySearchTreeTrait {
fn new(tree_data: Span<u32>) -> BinarySearchTree {
let mut bts: BinarySearchTree = Default::default();
for value in tree_data {
bts = bts.add(*value);
};
bts
}

fn add(self: BinarySearchTree, value: u32) -> BinarySearchTree {
match self {
Option::None => Option::Some(
BoxTrait::new(Node { value, left: Option::None, right: Option::None })
),
Option::Some(node) => {
if value <= node.value {
Option::Some(
BoxTrait::new(
Node {
value: node.value, left: node.left.add(value), right: node.right
}
)
)
} else {
Option::Some(
BoxTrait::new(
Node {
value: node.value, left: node.left, right: node.right.add(value)
}
)
)
}
}
}
}

fn value(self: @BinarySearchTree) -> Option<u32> {
Option::Some((*self)?.value)
}

fn left(self: @BinarySearchTree) -> @BinarySearchTree {
@match self {
Option::None => Option::None,
Option::Some(bst) => bst.left
}
}

fn right(self: @BinarySearchTree) -> @BinarySearchTree {
@match self {
Option::None => Option::None,
Option::Some(bst) => bst.right
}
}

fn sorted_data(self: @BinarySearchTree) -> Span<u32> {
let mut res = array![];
if let Option::Some(node) = self {
res.append_span(node.left.sorted_data());
res.append(node.value);
res.append_span(node.right.sorted_data());
}
res.span()
}
}
40 changes: 40 additions & 0 deletions exercises/practice/binary-search-tree/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[e9c93a78-c536-4750-a336-94583d23fafa]
description = "data is retained"

[7a95c9e8-69f6-476a-b0c4-4170cb3f7c91]
description = "insert data at proper node -> smaller number at left node"

[22b89499-9805-4703-a159-1a6e434c1585]
description = "insert data at proper node -> same number at left node"

[2e85fdde-77b1-41ed-b6ac-26ce6b663e34]
description = "insert data at proper node -> greater number at right node"

[dd898658-40ab-41d0-965e-7f145bf66e0b]
description = "can create complex tree"

[9e0c06ef-aeca-4202-b8e4-97f1ed057d56]
description = "can sort data -> can sort single number"

[425e6d07-fceb-4681-a4f4-e46920e380bb]
description = "can sort data -> can sort if second number is smaller than first"

[bd7532cc-6988-4259-bac8-1d50140079ab]
description = "can sort data -> can sort if second number is same as first"

[b6d1b3a5-9d79-44fd-9013-c83ca92ddd36]
description = "can sort data -> can sort if second number is greater than first"

[d00ec9bd-1288-4171-b968-d44d0808c1c8]
description = "can sort data -> can sort complex tree"
7 changes: 7 additions & 0 deletions exercises/practice/binary-search-tree/Scarb.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "binary_search_tree"
version = "0.1.0"
edition = "2024_07"

[dev-dependencies]
cairo_test = "2.8.2"
31 changes: 31 additions & 0 deletions exercises/practice/binary-search-tree/src/lib.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
type BinarySearchTree = Option<Box<Node>>;

#[derive(Drop, Copy)]
struct Node {
value: u32,
left: BinarySearchTree,
right: BinarySearchTree,
}

#[generate_trait]
pub impl BinarySearchTreeImpl of BinarySearchTreeTrait {
fn new(tree_data: Span<u32>) -> BinarySearchTree {
panic!("implement `BinarySearchTreeTrait::new`")
}

fn value(self: @BinarySearchTree) -> Option<u32> {
panic!("implement `BinarySearchTreeTrait::value`")
}

fn left(self: @BinarySearchTree) -> @BinarySearchTree {
panic!("implement `BinarySearchTreeTrait::left`")
}

fn right(self: @BinarySearchTree) -> @BinarySearchTree {
panic!("implement `BinarySearchTreeTrait::right`")
}

fn sorted_data(self: @BinarySearchTree) -> Span<u32> {
panic!("implement `BinarySearchTreeTrait::sorted_data`")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use binary_search_tree::BinarySearchTreeTrait as BinarySearchTree;

#[test]
fn data_is_retained() {
let bst = BinarySearchTree::new(array![4].span());
assert_eq!(Option::Some(4), bst.value());
}

#[test]
fn smaller_number_at_left_node() {
let bst = BinarySearchTree::new(array![4, 2].span());
assert_eq!(Option::Some(4), bst.value());
assert_eq!(Option::Some(2), bst.left().value());
}

#[test]
fn same_number_at_left_node() {
let bst = BinarySearchTree::new(array![4, 4].span());
assert_eq!(Option::Some(4), bst.value());
assert_eq!(Option::Some(4), bst.left().value());
}

#[test]
fn greater_number_at_right_node() {
let bst = BinarySearchTree::new(array![4, 5].span());
assert_eq!(Option::Some(4), bst.value());
assert_eq!(Option::Some(5), bst.right().value());
}

#[test]
fn can_create_complex_tree() {
let bst = BinarySearchTree::new(array![4, 2, 6, 1, 3, 5, 7].span());
assert_eq!(Option::Some(4), bst.value());
assert_eq!(Option::Some(2), bst.left().value());
assert_eq!(Option::Some(6), bst.right().value());
assert_eq!(Option::Some(1), bst.left().left().value());
assert_eq!(Option::Some(3), bst.left().right().value());
assert_eq!(Option::Some(5), bst.right().left().value());
assert_eq!(Option::Some(7), bst.right().right().value());
}

#[test]
fn can_sort_single_number() {
let mut bts = BinarySearchTree::new(array![2].span());
let expected = array![2].span();
assert_eq!(expected, bts.sorted_data());
}

#[test]
fn can_sort_if_second_number_is_smaller_than_first() {
let mut bts = BinarySearchTree::new(array![2, 1].span());
let expected = array![1, 2].span();
assert_eq!(expected, bts.sorted_data());
}

#[test]
fn can_sort_if_second_number_is_same_as_first() {
let mut bts = BinarySearchTree::new(array![2, 2].span());
let expected = array![2, 2].span();
assert_eq!(expected, bts.sorted_data());
}

#[test]
fn can_sort_if_second_number_is_greater_than_first() {
let mut bts = BinarySearchTree::new(array![2, 3].span());
let expected = array![2, 3].span();
assert_eq!(expected, bts.sorted_data());
}

#[test]
fn can_sort_complex_tree() {
let mut bts = BinarySearchTree::new(array![2, 1, 3, 6, 7, 5].span());
let expected = array![1, 2, 3, 5, 6, 7].span();
assert_eq!(expected, bts.sorted_data());
}

0 comments on commit 2f5bd88

Please sign in to comment.