I believe that you would do better with a different data representation:
struct NaiveTreeNode {
left: Option<~NaiveTreeNode>,
right: Option<~NaiveTreeNode>,
key: int,
val: char,
}
This will be easier to work with and is slightly more efficient (Option<~T>
can be represented as a nullable pointer, while your current solution has a leaf node still requiring a pointer lookup to check if it's NNil
).
You don't need to implement your eq
method; it can be derived, an implementation of the Eq
trait, by putting #[deriving(Eq)]
immediately before the struct.
Of your add_branch
method, you must understand that self.add_branch
is a method bound to self
. When you call self.add_branch(l_branch, node_to_add)
, that is invalid, for you are passing two arguments to one expecting one. What you meant was l_branch.add_branch(node_to_add)
.
I've restructured the add_branch
method significantly; here's the complete code that I would write:
#[deriving(Eq)]
struct NaiveTreeNode {
left: Option<~NaiveTreeNode>,
right: Option<~NaiveTreeNode>,
key: int,
val: char,
}
impl NaiveTreeNode {
fn add_branch(&mut self, node: ~NaiveTreeNode) {
match (self.key.cmp(node.key), self.left, self.right) {
(Greater, None, _) => self.left = Some(node),
(Greater, Some(~ref mut left), _) => left.add_branch(node),
(Less, _, None) => self.right = Some(node),
(Less, _, Some(~ref mut right)) => right.add_branch(node),
(Equal, _, _) => fail!("this tree already has a node with key {} \
(value {}, attempted value {})",
self.key, self.value, node.value),
}
}
}
The match could also be expanded to the following, if you desired:
match self.key.cmp(node.key) {
Greater => match self.left {
None => self.left = Some(node),
Some(~ref mut left) => left.add_branch(node),
},
Less => match self.right {
None => self.right = Some(node),
Some(~ref mut right) => right.add_branch(node),
},
Equal => fail!("this tree already has a node with key {} \
(value {}, attempted value {})",
self.key, self.value, node.value),
}
If there's anything you don't understand in this code, just holler and I'll explain it.