Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created July 6, 2021 16:24
Show Gist options
  • Save alfonmga/978de58f0a717e117e0f988c6366ac7a to your computer and use it in GitHub Desktop.
Save alfonmga/978de58f0a717e117e0f988c6366ac7a to your computer and use it in GitHub Desktop.
Rust: binary tree lexically ordered
fn insert(&mut self, data: &str) {
if data < &self.payload {
match self.left {
Some(ref mut n) => n.insert(data),
None => self.set_left(Self::new(data)),
}
} else {
match self.right {
Some(ref mut n) => n.insert(data),
None => self.set_right(Self::new(data)),
}
}
}
...
fn main() {
let mut root = Node::new("root");
root.insert("one");
root.insert("two");
root.insert("four");
println!("root {:#?}", root);
}
@alfonmga
Copy link
Author

alfonmga commented Jul 6, 2021

Output result:

root Node {
    payload: "root",
    left: Some(
        Node {
            payload: "one",
            left: Some(
                Node {
                    payload: "four",
                    left: None,
                    right: None
                }
            ),
            right: None
        }
    ),
    right: Some(
        Node {
            payload: "two",
            left: None,
            right: None
        }
    )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment