|
@@ -5,6 +5,7 @@ struct Node {
|
|
|
left: Option<Box<Self>>,
|
|
left: Option<Box<Self>>,
|
|
|
right: Option<Box<Self>>,
|
|
right: Option<Box<Self>>,
|
|
|
character: Option<char>,
|
|
character: Option<char>,
|
|
|
|
|
+ frequency: i32,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
impl Node {
|
|
impl Node {
|
|
@@ -13,22 +14,26 @@ impl Node {
|
|
|
left: None,
|
|
left: None,
|
|
|
right: None,
|
|
right: None,
|
|
|
character: None,
|
|
character: None,
|
|
|
|
|
+ frequency: 0,
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- pub fn new_with_character(character: char) -> Node {
|
|
|
|
|
|
|
+ pub fn new_with_character(character: char, frequency: i32) -> Node {
|
|
|
Self {
|
|
Self {
|
|
|
character: Some(character),
|
|
character: Some(character),
|
|
|
left: None,
|
|
left: None,
|
|
|
right: None,
|
|
right: None,
|
|
|
|
|
+ frequency
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
pub fn join_left(self: &mut Node, left: Box<Node>) {
|
|
pub fn join_left(self: &mut Node, left: Box<Node>) {
|
|
|
|
|
+ self.frequency += left.get_frequency();
|
|
|
self.left = Some(left);
|
|
self.left = Some(left);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
pub fn join_right(self: &mut Node, right: Box<Node>) {
|
|
pub fn join_right(self: &mut Node, right: Box<Node>) {
|
|
|
|
|
+ self.frequency += right.get_frequency();
|
|
|
self.right = Some(right);
|
|
self.right = Some(right);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -36,6 +41,10 @@ impl Node {
|
|
|
self.left.is_none() & self.right.is_none()
|
|
self.left.is_none() & self.right.is_none()
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ pub fn get_frequency(self: &Node) -> i32 {
|
|
|
|
|
+ self.frequency
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
pub fn get_character(self: &Node) -> Result<char, &str> {
|
|
pub fn get_character(self: &Node) -> Result<char, &str> {
|
|
|
if !self.is_leaf() {
|
|
if !self.is_leaf() {
|
|
|
return Err("This node is not a leaf node.");
|
|
return Err("This node is not a leaf node.");
|
|
@@ -44,3 +53,31 @@ impl Node {
|
|
|
Ok(self.character.unwrap())
|
|
Ok(self.character.unwrap())
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+#[cfg(test)]
|
|
|
|
|
+mod test {
|
|
|
|
|
+ #[test]
|
|
|
|
|
+ fn make_new_node_with_character_works() {
|
|
|
|
|
+ use crate::Node;
|
|
|
|
|
+
|
|
|
|
|
+ let example = Node::new_with_character('a', 5);
|
|
|
|
|
+ assert!(example.is_leaf());
|
|
|
|
|
+ assert_eq!(example.get_character().unwrap(), 'a');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ #[test]
|
|
|
|
|
+ fn make_small_tree_with_leaf_nodes() {
|
|
|
|
|
+ use crate::Node;
|
|
|
|
|
+
|
|
|
|
|
+ let mut root = Node::new();
|
|
|
|
|
+ let left = Node::new_with_character('a', 5);
|
|
|
|
|
+ let right = Node::new_with_character('b', 10);
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ root.join_left(Box::new(left));
|
|
|
|
|
+ root.join_right(Box::new(right));
|
|
|
|
|
+
|
|
|
|
|
+ assert!(!root.is_leaf());
|
|
|
|
|
+ assert_eq!(root.get_frequency(), 15);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|