Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. #![allow(unused)]
  2.  
  3. use std::iter::{empty as empty_iter, once};
  4.  
  5. #[derive(Debug, PartialEq)]
  6. enum BST<T> {
  7. Empty,
  8. Node {
  9. value: T,
  10. left: Box<BST<T>>,
  11. right: Box<BST<T>>,
  12. }
  13. }
  14.  
  15. impl<T: PartialOrd> BST<T> {
  16. /// Return leaf node
  17. fn leaf(value: T) -> Self {
  18. BST::Node{
  19. value,
  20. left: Box::new(BST::Empty),
  21. right: Box::new(BST::Empty),
  22. }
  23. }
  24.  
  25. /// Associate function
  26. fn is_empty(&self) -> bool {
  27. match *self {
  28. BST::Empty => true,
  29. _ => false,
  30. }
  31. }
  32.  
  33. /// Insert a node
  34. fn insert(&mut self, to_insert: T) {
  35. match self {
  36. BST::Empty => *self = BST::leaf(to_insert),
  37. BST::Node {value, left, right} => {
  38. if to_insert < *value {
  39. left.insert(to_insert);
  40. } else {
  41. right.insert(to_insert);
  42. }
  43. },
  44. }
  45. }
  46.  
  47. /// in order
  48. fn in_order_iter(&'static self) -> Box<dyn Iterator<Item = &T>> {
  49. match self {
  50. BST::Empty => Box::new(empty_iter()) as Box<dyn Iterator<Item = &T>>,
  51. BST::Node { value, left, right } => Box::new(
  52. left.in_order_iter()
  53. .chain(once(value))
  54. .chain(right.in_order_iter())
  55. ) as Box<dyn Iterator<Item = &T>>,
  56. }
  57. }
  58.  
  59. /// Get mutable min value ref
  60. fn min_mut(&mut self) -> Option<&mut T> {
  61. match self {
  62. BST::Empty => None,
  63. BST::Node {value, left, ..} => {
  64. if left.is_empty() {
  65. Some(value)
  66. } else {
  67. left.min_mut()
  68. }
  69. }
  70. }
  71. }
  72.  
  73. /// remove
  74. fn remove(&mut self, to_remove: T) {
  75. match self {
  76. BST::Empty => {},
  77. BST::Node {value, left, right} => {
  78. if to_remove < *value {
  79. left.remove(to_remove);
  80. } else if to_remove > *value {
  81. right.remove(to_remove);
  82. } else {
  83. match (&**left, &**right) {
  84. (BST::Empty, BST::Empty) => (),
  85. (_, BST::Empty) => *self = std::mem::replace(&mut **left, BST::Empty),
  86. (BST::Empty, _) => *self = std::mem::replace(&mut **right, BST::Empty),
  87. _ => {
  88. std::mem::swap(value, right.min_mut().unwrap());
  89. right.remove(to_remove);
  90. }
  91. }
  92. }
  93. }
  94. }
  95. }
  96. }
  97.  
  98. fn main() {
  99. let root = BST::leaf(5);
  100. dbg!(root.is_empty());
  101. dbg!(root);
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement