Skip to content

Instantly share code, notes, and snippets.

@Killavus
Created October 14, 2017 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Killavus/07fe76221aa4ef41edd0a4a858695efd to your computer and use it in GitHub Desktop.
Save Killavus/07fe76221aa4ef41edd0a4a858695efd to your computer and use it in GitHub Desktop.
struct TreeNode<T>
where T: Ord
{
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
impl TreeNode<T>
where T: Ord
{
fn step(&self, value: &T) -> Option<&TreeNode<T>> {
match value.cmp(&self.value) {
Ordering::Less => self.left.as_ref().map(|node_box| node_box.deref()),
Ordering::Equal => Some(&self),
Ordering::Greater => self.right.as_ref().map(|node_box| node_box.deref()),
}
}
fn step_mut(&mut self, value: &T) -> Option<&mut TreeNode<T>> {
match value.cmp(&self.value) {
Ordering::Less => self.left.as_mut().map(|node_box| node_box.deref_mut()),
Ordering::Equal => Some(self),
Ordering::Greater => self.right.as_mut().map(|node_box| node_box.deref_mut()),
}
}
fn parent(&self, value: &T) -> &TreeNode<T> {
let mut cursor = self;
while let Some(next_node) = cursor.step(value) {
if next_node.value == *value {
return cursor;
}
cursor = next_node;
}
return cursor;
}
fn parent_mut(&mut self, value: &T) -> &mut TreeNode<T> {
let mut cursor = self;
while let Some(next_node) = cursor.step_mut(value) {
if next_node.value == *value {
return cursor;
}
cursor = next_node;
}
return cursor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment