#Skip to menu

Rust: Binary Search Tree

Published:

In this article we’ll see how to implement a Binary Search Tree in Rust. You can also get the final source code.

Node

A tree is composed of nodes. Each node has a key, a value and two sub-trees: a left one and a right one. We want to be able to store integers, strings, structs or any other data structure in our BST, so we use generics both for the key and the value. A node doesn’t always have sub-trees, and we use Option to represent the possibility of presence or absence. Here is the Node struct:

Rust has many types of pointers, the most important ones are: references (&T) and Boxes.

  • References (&T) borrow a resource for a limited time. They don’t own the resource and are valid as long as the resource they point to is valid.
  • Boxes instead own the resource they point to. When the Box goes out of scope the resource is deallocated.

Here’s an example:

As you can see we can only reference a Node while we are inside its scope. What we need instead is to own the Node we refer to…

Methods

We need a method to create a new node given a key and a value:

BSTs are sorted which means that nodes on the left are less than the current node and those on the right are greater. How we decide if your generic type K is lesser or greater? We use a trait constrain which says that our key can be of any type as long as said type implements the Ord trait.

The insert method is defined recursively. If the Node to be inserted is less follow the left sub-tree, if it’s greater follow the right one, otherwise do nothing.

We do a similar thing with get.

Instead of letting the user manipulate Nodes, we use another struct called Bst which holds the root of our tree and optionally other fields (like the length of the tree).

Here is an example

Traits

To make our BST more ergonomic to use, we need to implement some traits from the standard library.

Index

With this trait we can do bst[2] instead of bst.get(2).

Iter

TODO

derive

Rust (like Haskell) can automaticaly implement some traits, when asked to do so, using the derive attribute. Add…

…and…

this will implement the Debug and Default traits.

Grapvhiz

Graphviz is a graph visualization software. We can generate a DOT file and pass the output to the dot program which will generate the graph of our tree.

Download the example and run it:

$ rustc dot.rs -o /tmp/dot && /tmp/dot | dot -Tx11

Source code

bst.rs dot.rs

Exercises for the reader

  • Implement a remove method.
  • Implement a length method on Bst. One way is to recursively calculate each time the length of the tree, the other is to have a length field in struct Bst and make insert return a true if a new node was inserted, false otherwise (the same for remove).
  • Implement a self-balancing tree (for example a Splay Tree).
  • Implement the IndexMut trait.

See all the discussions around the web about this page.