Created
June 21, 2014 03:36
-
-
Save mveytsman/ec725562602a4c5d8179 to your computer and use it in GitHub Desktop.
binary search tree in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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