Exercise: Binary Tree

A binary tree is a tree-type data structure where every node has two children (left and right). We will create a tree where each node stores a value. For a given node N, all nodes in a N’s left subtree contain smaller values, and all nodes in N’s right subtree will contain larger values.

Implement the following types, so that the given tests pass.

Extra Credit: implement an iterator over a binary tree that returns the values in order.

  1. /// A node in the binary tree.
  2. #[derive(Debug)]
  3. struct Node<T: Ord> {
  4. value: T,
  5. left: Subtree<T>,
  6. right: Subtree<T>,
  7. }
  8. /// A possibly-empty subtree.
  9. #[derive(Debug)]
  10. struct Subtree<T: Ord>(Option<Box<Node<T>>>);
  11. /// A container storing a set of values, using a binary tree.
  12. ///
  13. /// If the same value is added multiple times, it is only stored once.
  14. #[derive(Debug)]
  15. pub struct BinaryTree<T: Ord> {
  16. root: Subtree<T>,
  17. }
  18. impl<T: Ord> BinaryTree<T> {
  19. fn new() -> Self {
  20. Self { root: Subtree::new() }
  21. }
  22. fn insert(&mut self, value: T) {
  23. self.root.insert(value);
  24. }
  25. fn has(&self, value: &T) -> bool {
  26. self.root.has(value)
  27. }
  28. fn len(&self) -> usize {
  29. self.root.len()
  30. }
  31. }
  32. // Implement `new`, `insert`, `len`, and `has` for `Subtree`.
  33. #[cfg(test)]
  34. mod tests {
  35. use super::*;
  36. #[test]
  37. fn len() {
  38. let mut tree = BinaryTree::new();
  39. assert_eq!(tree.len(), 0);
  40. tree.insert(2);
  41. assert_eq!(tree.len(), 1);
  42. tree.insert(1);
  43. assert_eq!(tree.len(), 2);
  44. tree.insert(2); // not a unique item
  45. assert_eq!(tree.len(), 2);
  46. }
  47. #[test]
  48. fn has() {
  49. let mut tree = BinaryTree::new();
  50. fn check_has(tree: &BinaryTree<i32>, exp: &[bool]) {
  51. let got: Vec<bool> =
  52. (0..exp.len()).map(|i| tree.has(&(i as i32))).collect();
  53. assert_eq!(&got, exp);
  54. }
  55. check_has(&tree, &[false, false, false, false, false]);
  56. tree.insert(0);
  57. check_has(&tree, &[true, false, false, false, false]);
  58. tree.insert(4);
  59. check_has(&tree, &[true, false, false, false, true]);
  60. tree.insert(4);
  61. check_has(&tree, &[true, false, false, false, true]);
  62. tree.insert(3);
  63. check_has(&tree, &[true, false, false, true, true]);
  64. }
  65. #[test]
  66. fn unbalanced() {
  67. let mut tree = BinaryTree::new();
  68. for i in 0..100 {
  69. tree.insert(i);
  70. }
  71. assert_eq!(tree.len(), 100);
  72. assert!(tree.has(&50));
  73. }
  74. }