Instantiate an object without giving parameter
A useful pattern when designing a tree type is to make the “public” (or at least the usually-used) type of your tree be the one that might contain a node rather than one that definitely is a node. For example,
pub struct BST {
node: Option<Box<BSTNode>>,
}
struct BSTNode {
value: i32,
left: BST,
right: BST,
}
This way, a value of type BST
can contain any number of values, including none.
Or, you could define it as a single enum:
pub enum BST {
Empty,
Node {
value: i32,
left: Box<BST>,
right: Box<BST>,
}
}
This is the simplest data structure that will work, but it has the disadvantage of allocating a Box
for every Empty
leaf. If you rearrange things to avoid that, then you'll end up back at Option
or a 2-variant enum equivalent to Option
. So, I'd recommend the first version I showed, which only has as many Box
es as value
s.