node and bits

This commit is contained in:
2025-04-07 20:12:04 +02:00
parent ebd3e33a03
commit c4c0c32f0e
6 changed files with 174 additions and 11 deletions

43
src/node.rs Normal file
View File

@@ -0,0 +1,43 @@
pub struct Node {
pub val: Option<Box<char>>,
pub l: Option<Box<Node>>,
pub r: Option<Box<Node>>,
pub n: i32,
}
impl Node {
pub fn new() -> Self {
Node {
val: None,
l: None,
r: None,
n: 0,
}
}
pub fn set_char(&mut self, v: char) {
self.val = Some(Box::new(v));
}
pub fn set_counter(&mut self, n: i32) {
self.n = n;
}
pub fn insert(&mut self, l: Node, r: Node) {
self.l = Some(Box::new(l));
self.r = Some(Box::new(r));
}
}
pub fn create_tree(mut nodes: Vec<Node>) -> Node {
while nodes.len() > 1 {
nodes.sort_by_key(|node| node.n);
let mut new_root = Node::new();
let l = nodes.remove(0);
let r = nodes.remove(0);
new_root.set_counter(l.n + r.n);
new_root.insert(l, r);
nodes.push(new_root);
}
nodes.pop().unwrap()
}