Advertisement
Guest User

Rust AVL Tree

a guest
Mar 23rd, 2020
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 5.86 KB | None | 0 0
  1. // Завдання: написати програму, яка створює збалансоване бінарне дерево. Написати рекурсивну функцію, що підраховує суму елементів дерева.
  2.  
  3.  
  4. use std::{
  5.     cmp::{max, Ordering},
  6.     iter::{self, FromIterator},
  7.     mem,
  8. };
  9.  
  10. fn main() {
  11.     let tree: Tree = vec![5, 15, 16, 3, 6, 7, 2, 1, 4].into_iter().collect();
  12.     tree.print();
  13.     println!("{}", tree.product());
  14. }
  15.  
  16. struct Tree {
  17.     root: Option<Node>,
  18. }
  19.  
  20. impl Tree {
  21.     fn new() -> Self {
  22.         Self { root: None }
  23.     }
  24.  
  25.     fn insert(&mut self, value: i64) {
  26.         match &mut self.root {
  27.             Some(root) => root.insert(value),
  28.             None => self.root = Some(Node::new(value)),
  29.         }
  30.     }
  31.  
  32.     fn product(&self) -> i64 {
  33.         let root = match &self.root {
  34.             Some(root) => root,
  35.             None => return 1,
  36.         };
  37.  
  38.         root.get_all_children()
  39.             .iter()
  40.             .chain(iter::once(&root))
  41.             .map(|node| node.value)
  42.             .product()
  43.     }
  44.  
  45.     fn print(&self) {
  46.         match &self.root {
  47.             Some(root) => root.print(0),
  48.             None => println!("The tree is empty"),
  49.         }
  50.     }
  51. }
  52.  
  53. impl FromIterator<i64> for Tree {
  54.     fn from_iter<T: IntoIterator<Item = i64>>(iter: T) -> Self {
  55.         let mut tree = Tree::new();
  56.         iter.into_iter().for_each(|x| tree.insert(x));
  57.         tree
  58.     }
  59. }
  60.  
  61. enum RotationType {
  62.     NoRotation,
  63.     LL,
  64.     RR,
  65.     LR,
  66.     RL,
  67. }
  68.  
  69. struct Node {
  70.     value: i64,
  71.     left: Option<Box<Node>>,
  72.     right: Option<Box<Node>>,
  73. }
  74.  
  75. impl Node {
  76.     fn new(value: i64) -> Self {
  77.         Self {
  78.             value,
  79.             left: None,
  80.             right: None,
  81.         }
  82.     }
  83.  
  84.     fn insert(&mut self, value: i64) {
  85.         let branch = match value.cmp(&self.value) {
  86.             Ordering::Less => &mut self.left,
  87.             Ordering::Greater => &mut self.right,
  88.             Ordering::Equal => panic!("duplicate value: {}", value),
  89.         };
  90.  
  91.         match branch {
  92.             Some(branch) => branch.insert(value),
  93.             None => *branch = Some(Box::new(Node::new(value))),
  94.         }
  95.  
  96.         self.rebalance();
  97.     }
  98.  
  99.     fn rebalance(&mut self) {
  100.         match self.pick_rotation_type() {
  101.             RotationType::NoRotation => (),
  102.             RotationType::LL => self.rotate_ll(),
  103.             RotationType::RR => self.rotate_rr(),
  104.             RotationType::LR => self.rotate_lr(),
  105.             RotationType::RL => self.rotate_rl(),
  106.         }
  107.     }
  108.  
  109.     fn pick_rotation_type(&self) -> RotationType {
  110.         match self.balance_factor() {
  111.             -1 | 0 | 1 => RotationType::NoRotation,
  112.             2 => match self.left.as_ref().unwrap().balance_factor() {
  113.                 0 | 1 | 2 => RotationType::LL,
  114.                 -2 | -1 => RotationType::LR,
  115.                 bf => panic!("unexpected balance factor: {}", bf),
  116.             },
  117.             -2 => match self.right.as_ref().unwrap().balance_factor() {
  118.                 -2 | -1 | 0 => RotationType::RR,
  119.                 1 | 2 => RotationType::RL,
  120.                 bf => panic!("unexpected balance factor: {}", bf),
  121.             },
  122.             bf => panic!("unexpected balance factor: {}", bf),
  123.         }
  124.     }
  125.  
  126.     fn rotate_ll(&mut self) {
  127.         let parent = self;
  128.  
  129.         let mut left = parent.left.take().unwrap();
  130.         mem::swap(parent, &mut left);
  131.         match &mut parent.right {
  132.             Some(right) => {
  133.                 mem::swap(right, &mut left);
  134.                 right.left = Some(left);
  135.             }
  136.             None => parent.right = Some(left),
  137.         }
  138.     }
  139.  
  140.     fn rotate_rr(&mut self) {
  141.         let parent = self;
  142.  
  143.         let mut right = parent.right.take().unwrap();
  144.         mem::swap(parent, &mut right);
  145.         match &mut parent.left {
  146.             Some(left) => {
  147.                 mem::swap(left, &mut right);
  148.                 left.right = Some(right);
  149.             }
  150.             None => parent.left = Some(right),
  151.         }
  152.     }
  153.  
  154.     fn rotate_lr(&mut self) {
  155.         self.left.as_mut().unwrap().rotate_rr();
  156.         self.rotate_ll();
  157.     }
  158.  
  159.     fn rotate_rl(&mut self) {
  160.         self.right.as_mut().unwrap().rotate_ll();
  161.         self.rotate_rr();
  162.     }
  163.  
  164.     fn get_all_children(&self) -> Vec<&Node> {
  165.         let mut children = Vec::with_capacity(2);
  166.         if let Some(left) = self.left.as_deref() {
  167.             children.push(left);
  168.             children.extend(left.get_all_children());
  169.         }
  170.  
  171.         if let Some(right) = self.right.as_deref() {
  172.             children.push(right);
  173.             children.extend(right.get_all_children());
  174.         }
  175.  
  176.         children
  177.     }
  178.  
  179.     fn balance_factor(&self) -> i8 {
  180.         (self.left_branch_height() as i64 - self.right_branch_height() as i64) as i8
  181.     }
  182.  
  183.     fn height(&self) -> usize {
  184.         1 + max(self.left_branch_height(), self.right_branch_height())
  185.     }
  186.  
  187.     fn left_branch_height(&self) -> usize {
  188.         self.left.as_ref().map_or(0, |node| node.height())
  189.     }
  190.  
  191.     fn right_branch_height(&self) -> usize {
  192.         self.right.as_ref().map_or(0, |node| node.height())
  193.     }
  194.  
  195.     fn print(&self, indentation: usize) {
  196.         println!("{} {}", "    ".repeat(indentation), self.value,);
  197.         match (&self.left, &self.right) {
  198.             (Some(left), Some(right)) => {
  199.                 left.print(indentation + 1);
  200.                 right.print(indentation + 1);
  201.             }
  202.             (Some(left), None) => {
  203.                 left.print(indentation + 1);
  204.                 println!("{} -", "    ".repeat(indentation + 1));
  205.             }
  206.             (None, Some(right)) => {
  207.                 println!("{} -", "    ".repeat(indentation + 1));
  208.                 right.print(indentation + 1);
  209.             }
  210.             (None, None) => {}
  211.         }
  212.     }
  213. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement