二叉树

  1. use std::cmp::Ordering;
  2. use std::ops::Deref;
  3. /// This struct implements as Binary Search Tree (BST), which is a
  4. /// simple data structure for storing sorted data
  5. pub struct BinarySearchTree<T>
  6. where
  7. T: Ord,
  8. {
  9. value: Option<T>,
  10. left: Option<Box<BinarySearchTree<T>>>,
  11. right: Option<Box<BinarySearchTree<T>>>,
  12. }
  13. impl<T> Default for BinarySearchTree<T>
  14. where
  15. T: Ord,
  16. {
  17. fn default() -> Self {
  18. Self::new()
  19. }
  20. }
  21. impl<T> BinarySearchTree<T>
  22. where
  23. T: Ord,
  24. {
  25. /// Create a new, empty BST
  26. pub fn new() -> BinarySearchTree<T> {
  27. BinarySearchTree {
  28. value: None,
  29. left: None,
  30. right: None,
  31. }
  32. }
  33. /// Find a value in this tree. Returns True iff value is in this
  34. /// tree, and false otherwise
  35. pub fn search(&self, value: &T) -> bool {
  36. match &self.value {
  37. Some(key) => {
  38. match key.cmp(value) {
  39. Ordering::Equal => {
  40. // key == value
  41. true
  42. }
  43. Ordering::Greater => {
  44. // key > value
  45. match &self.left {
  46. Some(node) => node.search(value),
  47. None => false,
  48. }
  49. }
  50. Ordering::Less => {
  51. // key < value
  52. match &self.right {
  53. Some(node) => node.search(value),
  54. None => false,
  55. }
  56. }
  57. }
  58. }
  59. None => false,
  60. }
  61. }
  62. /// Returns a new iterator which iterates over this tree in order
  63. pub fn iter(&self) -> impl Iterator<Item = &T> {
  64. BinarySearchTreeIter::new(self)
  65. }
  66. /// Insert a value into the appropriate location in this tree.
  67. pub fn insert(&mut self, value: T) {
  68. if self.value.is_none() {
  69. self.value = Some(value);
  70. } else {
  71. match &self.value {
  72. None => (),
  73. Some(key) => {
  74. let target_node = if value < *key {
  75. &mut self.left
  76. } else {
  77. &mut self.right
  78. };
  79. match target_node {
  80. Some(ref mut node) => {
  81. node.insert(value);
  82. }
  83. None => {
  84. let mut node = BinarySearchTree::new();
  85. node.insert(value);
  86. *target_node = Some(Box::new(node));
  87. }
  88. }
  89. }
  90. }
  91. }
  92. }
  93. /// Returns the smallest value in this tree
  94. pub fn minimum(&self) -> Option<&T> {
  95. match &self.left {
  96. Some(node) => node.minimum(),
  97. None => match &self.value {
  98. Some(value) => Some(value),
  99. None => None,
  100. },
  101. }
  102. }
  103. /// Returns the largest value in this tree
  104. pub fn maximum(&self) -> Option<&T> {
  105. match &self.right {
  106. Some(node) => node.maximum(),
  107. None => match &self.value {
  108. Some(value) => Some(value),
  109. None => None,
  110. },
  111. }
  112. }
  113. /// Returns the largest value in this tree smaller than value
  114. pub fn floor(&self, value: &T) -> Option<&T> {
  115. match &self.value {
  116. Some(key) => {
  117. match key.cmp(value) {
  118. Ordering::Greater => {
  119. // key > value
  120. match &self.left {
  121. Some(node) => node.floor(value),
  122. None => None,
  123. }
  124. }
  125. Ordering::Less => {
  126. // key < value
  127. match &self.right {
  128. Some(node) => {
  129. let val = node.floor(value);
  130. match val {
  131. Some(_) => val,
  132. None => Some(key),
  133. }
  134. }
  135. None => Some(key),
  136. }
  137. }
  138. Ordering::Equal => Some(key),
  139. }
  140. }
  141. None => None,
  142. }
  143. }
  144. /// Returns the smallest value in this tree larger than value
  145. pub fn ceil(&self, value: &T) -> Option<&T> {
  146. match &self.value {
  147. Some(key) => {
  148. match key.cmp(value) {
  149. Ordering::Less => {
  150. // key < value
  151. match &self.right {
  152. Some(node) => node.ceil(value),
  153. None => None,
  154. }
  155. }
  156. Ordering::Greater => {
  157. // key > value
  158. match &self.left {
  159. Some(node) => {
  160. let val = node.ceil(value);
  161. match val {
  162. Some(_) => val,
  163. None => Some(key),
  164. }
  165. }
  166. None => Some(key),
  167. }
  168. }
  169. Ordering::Equal => {
  170. // key == value
  171. Some(key)
  172. }
  173. }
  174. }
  175. None => None,
  176. }
  177. }
  178. }
  179. struct BinarySearchTreeIter<'a, T>
  180. where
  181. T: Ord,
  182. {
  183. stack: Vec<&'a BinarySearchTree<T>>,
  184. }
  185. impl<'a, T> BinarySearchTreeIter<'a, T>
  186. where
  187. T: Ord,
  188. {
  189. pub fn new(tree: &BinarySearchTree<T>) -> BinarySearchTreeIter<T> {
  190. let mut iter = BinarySearchTreeIter { stack: vec![tree] };
  191. iter.stack_push_left();
  192. iter
  193. }
  194. fn stack_push_left(&mut self) {
  195. while let Some(child) = &self.stack.last().unwrap().left {
  196. self.stack.push(child);
  197. }
  198. }
  199. }
  200. impl<'a, T> Iterator for BinarySearchTreeIter<'a, T>
  201. where
  202. T: Ord,
  203. {
  204. type Item = &'a T;
  205. fn next(&mut self) -> Option<&'a T> {
  206. if self.stack.is_empty() {
  207. None
  208. } else {
  209. let node = self.stack.pop().unwrap();
  210. if node.right.is_some() {
  211. self.stack.push(node.right.as_ref().unwrap().deref());
  212. self.stack_push_left();
  213. }
  214. node.value.as_ref()
  215. }
  216. }
  217. }
  218. #[cfg(test)]
  219. mod test {
  220. use super::BinarySearchTree;
  221. fn prequel_memes_tree() -> BinarySearchTree<&'static str> {
  222. let mut tree = BinarySearchTree::new();
  223. tree.insert("hello there");
  224. tree.insert("general kenobi");
  225. tree.insert("you are a bold one");
  226. tree.insert("kill him");
  227. tree.insert("back away...I will deal with this jedi slime myself");
  228. tree.insert("your move");
  229. tree.insert("you fool");
  230. tree
  231. }
  232. #[test]
  233. fn test_search() {
  234. let tree = prequel_memes_tree();
  235. assert!(tree.search(&"hello there"));
  236. assert!(tree.search(&"you are a bold one"));
  237. assert!(tree.search(&"general kenobi"));
  238. assert!(tree.search(&"you fool"));
  239. assert!(tree.search(&"kill him"));
  240. assert!(
  241. !tree.search(&"but i was going to tosche station to pick up some power converters",)
  242. );
  243. assert!(!tree.search(&"only a sith deals in absolutes"));
  244. assert!(!tree.search(&"you underestimate my power"));
  245. }
  246. #[test]
  247. fn test_maximum_and_minimum() {
  248. let tree = prequel_memes_tree();
  249. assert_eq!(*tree.maximum().unwrap(), "your move");
  250. assert_eq!(
  251. *tree.minimum().unwrap(),
  252. "back away...I will deal with this jedi slime myself"
  253. );
  254. let mut tree2: BinarySearchTree<i32> = BinarySearchTree::new();
  255. assert!(tree2.maximum().is_none());
  256. assert!(tree2.minimum().is_none());
  257. tree2.insert(0);
  258. assert_eq!(*tree2.minimum().unwrap(), 0);
  259. assert_eq!(*tree2.maximum().unwrap(), 0);
  260. tree2.insert(-5);
  261. assert_eq!(*tree2.minimum().unwrap(), -5);
  262. assert_eq!(*tree2.maximum().unwrap(), 0);
  263. tree2.insert(5);
  264. assert_eq!(*tree2.minimum().unwrap(), -5);
  265. assert_eq!(*tree2.maximum().unwrap(), 5);
  266. }
  267. #[test]
  268. fn test_floor_and_ceil() {
  269. let tree = prequel_memes_tree();
  270. assert_eq!(*tree.floor(&"hello there").unwrap(), "hello there");
  271. assert_eq!(
  272. *tree
  273. .floor(&"these are not the droids you're looking for")
  274. .unwrap(),
  275. "kill him"
  276. );
  277. assert!(tree.floor(&"another death star").is_none());
  278. assert_eq!(*tree.floor(&"you fool").unwrap(), "you fool");
  279. assert_eq!(
  280. *tree.floor(&"but i was going to tasche station").unwrap(),
  281. "back away...I will deal with this jedi slime myself"
  282. );
  283. assert_eq!(
  284. *tree.floor(&"you underestimate my power").unwrap(),
  285. "you fool"
  286. );
  287. assert_eq!(*tree.floor(&"your new empire").unwrap(), "your move");
  288. assert_eq!(*tree.ceil(&"hello there").unwrap(), "hello there");
  289. assert_eq!(
  290. *tree
  291. .ceil(&"these are not the droids you're looking for")
  292. .unwrap(),
  293. "you are a bold one"
  294. );
  295. assert_eq!(
  296. *tree.ceil(&"another death star").unwrap(),
  297. "back away...I will deal with this jedi slime myself"
  298. );
  299. assert_eq!(*tree.ceil(&"you fool").unwrap(), "you fool");
  300. assert_eq!(
  301. *tree.ceil(&"but i was going to tasche station").unwrap(),
  302. "general kenobi"
  303. );
  304. assert_eq!(
  305. *tree.ceil(&"you underestimate my power").unwrap(),
  306. "your move"
  307. );
  308. assert!(tree.ceil(&"your new empire").is_none());
  309. }
  310. #[test]
  311. fn test_iterator() {
  312. let tree = prequel_memes_tree();
  313. let mut iter = tree.iter();
  314. assert_eq!(
  315. iter.next().unwrap(),
  316. &"back away...I will deal with this jedi slime myself"
  317. );
  318. assert_eq!(iter.next().unwrap(), &"general kenobi");
  319. assert_eq!(iter.next().unwrap(), &"hello there");
  320. assert_eq!(iter.next().unwrap(), &"kill him");
  321. assert_eq!(iter.next().unwrap(), &"you are a bold one");
  322. assert_eq!(iter.next().unwrap(), &"you fool");
  323. assert_eq!(iter.next().unwrap(), &"your move");
  324. assert_eq!(iter.next(), None);
  325. assert_eq!(iter.next(), None);
  326. }
  327. }