I am trying to implement a simple binary search tree in Rust but I am having difficulty pinning down an issue with inserting nodes. I am using the following data structures and functions.
enum BinaryTree<T> {
Leaf(T),
Branch(T, Box<BinaryTree<T>>, Box<BinaryTree<T>>),
Null,
}
fn createBinarySearchTree(vector: Vec<int>) -> BinaryTree<int> {
fn insertNode(val: int, btree: &BinaryTree<int>) -> BinaryTree<int> {
match btree {
&Leaf(tval) if val > tval => Branch(tval, box Null, box Leaf(val)),
&Leaf(tval) if val < tval => Branch(tval, box Leaf(val), box Null),
&Branch(tval, box ref left, box ref right) if val > tval => insertNode(val,right),
&Branch(tval, box ref left, box ref right) if val < tval => insertNode(val,left),
&Null => Leaf(val),
&Leaf(lval) if val == lval => Leaf(val),
&Branch(lval, box ref left, box ref right) if val == lval => fail!("already has a node with {}", lval),
_ => Null,
}
}
let mut tree = Null;
for v in vector.iter() {
tree = insertNode(*v, &tree);
}
let immuTree = tree;
immuTree
}
fn printTree(tree: &BinaryTree<int>) {
fn innerPrint(prefix: &str, tree: &BinaryTree<int>, level: int) {
let lvDesc = format!("lv {}", level);
match tree {
&Leaf(val) => println!("{}-{} leaf: {}", lvDesc, prefix, val),
&Branch(val, box ref left, box ref right) => {
println!("{}-{} node: {}", lvDesc, prefix, val);
innerPrint("left branch <-", left, level + 1);
innerPrint("right branch ->", right, level + 1);
},
&Null => println!("end"),
}
}
innerPrint("root", tree, 0);
}
Upon calling printTree(&createBinarySearchTree(vec![43,2,45,7,72,28,34,33]))
the tree only prints out 33,34
and unfortunately I cannot debug as compiling with debug info causes a compiler error. Also I have tried to return a branch when I match on branch on inserting but this requires me to clone the leaf/give ownership in ways that I just can't wrap my head around yet. So any help would be much appreciated
Cheers