Skip to content

Instantly share code, notes, and snippets.

@Mroik
Last active September 10, 2022 23:00
Show Gist options
  • Save Mroik/060151b9bdb778a80ab71104cc9beef2 to your computer and use it in GitHub Desktop.
Save Mroik/060151b9bdb778a80ab71104cc9beef2 to your computer and use it in GitHub Desktop.
use rand::Rng;
struct Node {
v: i32,
l: Option<Box<Node>>,
r: Option<Box<Node>>
}
fn make_node(v: i32) -> Node {
return Node {
v: v,
l: None,
r: None
}
}
fn print_order(root: &Node) {
match &root.l {
Some(lroot) => {
print_order(lroot);
},
None => {}
}
println!("{}", root.v);
match &root.r {
Some(rroot) => {
print_order(rroot);
},
None => {}
}
}
fn add_node(root: &mut Node, v: i32) {
if v < root.v {
if let Some(lroot) = &mut root.l {
add_node(lroot, v);
} else {
root.l = Some(Box::new(make_node(v)));
}
} else if v > root.v {
if let Some(rroot) = &mut root.r {
add_node(rroot,v);
} else {
root.r = Some(Box::new(make_node(v)));
}
}
}
fn main() {
let mut rng = rand::thread_rng();
let mut a: [i32; 100] = [0; 100];
for x in 0..100 {
a[x] = rng.gen_range(0..99);
}
let mut root = make_node(a[0]);
for x in 1..100 {
add_node(&mut root, a[x]);
}
print_order(&root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment