creat tree O(n²) -> O(nlog(n))

This commit is contained in:
2025-04-10 15:55:13 +02:00
parent 7fe27a0f38
commit 807de4ca65

View File

@@ -1,3 +1,4 @@
use std::collections::BTreeSet;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::VecDeque; use std::collections::VecDeque;
@@ -8,7 +9,25 @@ pub struct Node {
pub n: i32, pub n: i32,
pub path: String, pub path: String,
} }
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.n == other.n
}
}
impl Eq for Node {}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.n.cmp(&other.n)
}
}
impl Node { impl Node {
pub fn new() -> Self { pub fn new() -> Self {
Node { Node {
@@ -65,13 +84,19 @@ pub fn tree_to_map(root: &mut Node, char_to_bin: bool) -> HashMap<String, String
pub fn create_tree(mut nodes: Vec<Node>) -> Node { pub fn create_tree(mut nodes: Vec<Node>) -> Node {
while nodes.len() > 1 { while nodes.len() > 1 {
nodes.sort_by_key(|node| node.n); //nodes.sort_by_key(|node| node.n);
let mut new_root = Node::new(); let mut new_root = Node::new();
let l = nodes.remove(0); let l = nodes.remove(0);
let r = nodes.remove(0); let r = nodes.remove(0);
new_root.set_counter(l.n + r.n); new_root.set_counter(l.n + r.n);
new_root.insert(l, r); new_root.insert(l, r);
nodes.push(new_root); //nodes.push(new_root);
match nodes.binary_search(&new_root) {
Ok(_) => {}
Err(pos) => {
nodes.insert(pos, new_root);
}
}
} }
nodes.pop().unwrap() nodes.pop().unwrap()
} }