Advertisement
theultraman20

min_heap.rs

Aug 3rd, 2024 (edited)
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.70 KB | None | 0 0
  1.  
  2. use std::marker::PhantomData;
  3. use std::mem::swap;
  4.  
  5. //Min heap
  6. struct MinHeap<T> {
  7.     root: Option<Node<T>>,
  8.     phantom_data: PhantomData<T>,
  9. }
  10.  
  11. struct Node<T> {
  12.     left: Option<RefCell<Node<T>>>,
  13.     right: Option<RefCell<Node<T>>>,
  14.     parent: Option<RefCell<Node<T>>>,
  15.     elem: T,
  16.     child_count: usize,
  17.     phantom_data: PhantomData<T>,
  18. }
  19.  
  20. impl<T> Node<T> {
  21.     fn new(elem: T, parent: &Node<T>) -> Self {
  22.         Self {
  23.             left: None,
  24.             right: None,
  25.             elem: elem,
  26.             parent: RefCell::new(parent),
  27.             child_count: 0,
  28.             phantom_data: PhantomData,
  29.         }
  30.     }
  31. }
  32.  
  33. impl<T> MinHeap<T> {
  34.     fn new() -> MinHeap<T> {
  35.         MinHeap {
  36.             root: None,
  37.             phantom_data: PhantomData,
  38.         }
  39.     }
  40.  
  41.     fn get_min(&mut self) -> Option<T> {
  42.  
  43.  
  44.        
  45.  
  46.         todo!();
  47.     }
  48.  
  49.     //finds next node to insert element at
  50.     fn down_propogate(node: &RefCell<Node>) -> &mut Node {
  51.         if node.left == None || node.right == None {
  52.             node.parent.unwrap().borrow_mut()
  53.         } else if node.left.unwrap().child_count <= node.right.unwrap().child_count {
  54.             node.left.unwrap().borrow_mut().child_count += 1;
  55.             down_propogate(node.left.unwrap().borrow())
  56.         } else {
  57.             node.right.unwrap().borrow_mut().child_count += 1;
  58.             down_propogate(node.right.unwrap().borrow())
  59.         }
  60.     }
  61.  
  62.     fn insert(&mut self, elem: T) {
  63.         if self.root == None {
  64.             self.root = RefCell::new(Node::new(elem));
  65.             return;
  66.         }
  67.         //finds lowest node
  68.         let &mut node = down_propogate(self.root).borrow_mut();
  69.         node.child_count += 1;
  70.  
  71.         if node.left == None {
  72.             node.left = Some(RefCell::new(Node::new(elem)));
  73.         } else {
  74.             node.right = Some(RefCell::new(Node::new(elem)));
  75.         }
  76.  
  77.         //todo!();
  78.     }
  79.  
  80.     //possibly rename to pop
  81.     fn delete_min(&mut self) {
  82.         todo!();
  83.     }
  84.  
  85.     //...
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement