node and bits
This commit is contained in:
43
src/node.rs
Normal file
43
src/node.rs
Normal 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()
|
||||
}
|
||||
Reference in New Issue
Block a user