Guest User

Untitled

a guest
Oct 18th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. use std::cmp::Ordering;
  2.  
  3. enum BinaryTree<T> {
  4. Empty,
  5. NonEmpty(Box<TreeNode<T>>),
  6. }
  7.  
  8. struct TreeNode<T> {
  9. element: T,
  10. left: BinaryTree<T>,
  11. right: BinaryTree<T>,
  12. }
  13.  
  14. impl<T: Ord> BinaryTree<T> {
  15. fn add(&mut self, value: T) {
  16. match *self {
  17. BinaryTree::Empty => *self = BinaryTree::NonEmpty(Box::new(TreeNode { element: value, left: BinaryTree::Empty, right: BinaryTree::Empty})),
  18. BinaryTree::NonEmpty(ref mut node) =>
  19. if value <= node.element {
  20. node.left.add(value);
  21. } else {
  22. node.right.add(value);
  23. }
  24. }
  25. }
  26.  
  27. fn search(&self, value: T) -> Option<T> {
  28. match self {
  29. BinaryTree::Empty => None,
  30. BinaryTree::NonEmpty(node) => match node.element.cmp(&value) {
  31. Ordering::Equal => Some(value),
  32. Ordering::Less => node.right.search(value),
  33. Ordering::Greater => node.left.search(value),
  34. }
  35. }
  36. }
  37. }
  38.  
  39. fn main() {
  40. let mut tree = BinaryTree::Empty;
  41. tree.add(5);
  42. tree.add(6);
  43. tree.add(1);
  44. tree.add(4);
  45. tree.add(9);
  46.  
  47. let result = tree.search(5);
  48. println!("res {:?}", result);
  49.  
  50. println!("\nnext example");
  51. let result = tree.search(4);
  52. println!("res: {:?}", result);
  53.  
  54. println!("\nnext example");
  55. let result = tree.search(9);
  56. println!("res: {:?}", result);
  57.  
  58. println!("\nnext example");
  59. let result = tree.search(10);
  60. println!("res: {:?}", result);
  61. }
Add Comment
Please, Sign In to add comment