Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mveytsman
Created June 21, 2014 03:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mveytsman/ec725562602a4c5d8179 to your computer and use it in GitHub Desktop.
Save mveytsman/ec725562602a4c5d8179 to your computer and use it in GitHub Desktop.
binary search tree in rust
enum BinaryTree {
Node(int, Box<BinaryTree>, Box<BinaryTree>),
Leaf
}
fn insert(tree:Box<BinaryTree>, value:int) -> Box<BinaryTree> {
return box match (*tree) {
Leaf => Node(value, box Leaf, box Leaf),
Node(i, left, right) => if value < i {
Node(i, insert(left, value), right)
} else {
Node(i, left, insert(right, value))
}
};
}
fn print(tree:Box<BinaryTree>) -> () {
match tree {
box Leaf => (),
box Node(i, box Leaf, right) => {println!("{}",i); print(right)},
box Node(i, left, right) => {print(left); println!("{}",i); print(right)},
};
}
fn main() {
println!("Inserting 1,5,-11,12,-100,999,77 into tree");
let mut tree = box Leaf;
tree = insert(tree, 1);
tree = insert(tree, 5);
tree = insert(tree, -11);
tree = insert(tree, 12);
tree = insert(tree, -100);
tree = insert(tree, 999);
tree = insert(tree, 77);
print(tree);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment