translate work

This commit is contained in:
2025-04-09 00:57:43 +02:00
parent ea563518fd
commit d286ef66c1
4 changed files with 797 additions and 7 deletions

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::collections::VecDeque;
pub struct Node {
@@ -5,6 +6,7 @@ pub struct Node {
pub l: Option<Box<Node>>,
pub r: Option<Box<Node>>,
pub n: i32,
pub path: String,
}
impl Node {
@@ -14,6 +16,7 @@ impl Node {
l: None,
r: None,
n: 0,
path: String::new(),
}
}
@@ -31,6 +34,35 @@ impl Node {
}
}
pub fn tree_to_map(root: &mut Node, char_to_bin: bool) -> HashMap<String, String> {
let mut map: HashMap<String, String> = HashMap::new();
let mut to_do: VecDeque<&mut Node> = VecDeque::new();
to_do.push_back(root);
while let Some(int_root) = to_do.pop_front() {
if let Some(v) = int_root.val {
// leaf
if char_to_bin {
map.insert(v.to_string(), int_root.path.to_string());
} else {
map.insert(int_root.path.to_string(), v.to_string());
}
} else {
// internal
if let Some(l) = int_root.l.as_mut() {
l.path = format!("{}0", int_root.path);
to_do.push_back(l);
}
if let Some(r) = int_root.r.as_mut() {
r.path = format!("{}1", int_root.path);
to_do.push_back(r);
}
}
}
map
}
pub fn create_tree(mut nodes: Vec<Node>) -> Node {
while nodes.len() > 1 {
nodes.sort_by_key(|node| node.n);
@@ -78,9 +110,11 @@ pub fn read_tree(binary: &str, chars: &Vec<char>) -> Node {
let mut root = Node::new();
if stack_bin.remove(0) == '1' {
root.path = String::from("");
to_do.push_back(&mut root);
} else {
root.val = Some(stack_chars.remove(0));
root.path = String::from("0");
return root;
}
@@ -88,15 +122,19 @@ pub fn read_tree(binary: &str, chars: &Vec<char>) -> Node {
int_root.insert(Node::new(), Node::new());
if let Some(left) = int_root.l.as_mut() {
if stack_bin.remove(0) == '1' {
left.path = String::from("1");
to_do.push_back(left);
} else {
left.path = String::from("0");
left.val = Some(stack_chars.remove(0));
}
}
if let Some(right) = int_root.r.as_mut() {
if stack_bin.remove(0) == '1' {
to_do.push_front(right);
right.path = String::from("1");
to_do.push_back(right);
} else {
right.path = String::from("0");
right.val = Some(stack_chars.remove(0));
}
}