Created
November 21, 2024 20:13
-
-
Save 0ex-d/f21f81807c592e0f98846c9410c3ad00 to your computer and use it in GitHub Desktop.
Optimal Binary tree I use often in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct BinaryTree { | |
tree: Vec<u32>, | |
max_size: usize, | |
curr_size: usize, | |
} | |
impl BinaryTree { | |
fn new(max_size: usize) -> Self { | |
BinaryTree { | |
tree: vec![0; max_size + 1], // 1-based indexing | |
max_size, | |
curr_size: 0, | |
} | |
} | |
fn add(&mut self, value: u32) -> Result<(), String> { | |
if value == 0 { | |
return Err("Value must be non-zero".to_string()); | |
} | |
if self.curr_size >= self.max_size { | |
return Err("Tree is full".to_string()); | |
} | |
self.curr_size += 1; | |
self.tree[self.curr_size] = value; | |
Ok(()) | |
} | |
fn is_full(&self) -> bool { | |
self.curr_size >= self.max_size | |
} | |
fn get_tree(&self) -> Vec<u32> { | |
self.tree[1..=self.curr_size].to_vec() | |
} | |
} | |
fn main() { | |
let mut tree = BinaryTree::new(7); | |
let values = vec![10, 20, 30, 0, 40]; | |
for &val in &values { | |
match tree.add(val) { | |
Ok(_) => println!("Added {} to the tree.", val), | |
Err(err) => println!("Failed to add {}: {}", val, err), | |
} | |
} | |
println!("Tree: {:?}", tree.get_tree()); | |
println!("Is full? {}", tree.is_full()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment