{{#include exercise.rs:solution}}- Recursive Types with
Box:Noderefers toSubtree, which refers toNode(viaBox).Box<Node<T>>has a fixed size (pointer size), which breaks the cycle of infinite size that would occur ifNodedirectly contained otherNodes. - Nullability with
Option: We useOption<Box<Node<T>>>to represent a potentially empty subtree. Rust does not have null pointers;Optionis the standard way to express absence. - Newtype Pattern:
SubtreewrapsOption<Box<Node<T>>>. This allows us to define methods likeinsertandlendirectly onSubtree, keeping theNodelogic simple. It abstracts away the implementation detail that an empty tree isNone. - References in
match: Noticematch &self.0andmatch &mut self.0. We match on references to the innerOptionso that we can inspect or modify the tree without taking ownership of the nodes (which would destroy the tree).
Details
- Discuss why
Boxis needed. Without it,sizeof(Node)would depend onsizeof(Node), which is impossible to resolve. - This is a standard BST implementation. Since it's not balanced, performance can degrade to O(N) if elements are inserted in sorted order.