I want to implement a recursive inorder in a binary search tree (BST). I built a tree using two structs: Node
and Tree
. My code has not worked so far, mainly because of a type mismatch in Node::inorder
.
pub struct Node<T> {
value: T,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>,
}
pub struct Tree<T> {
root: Option<Box<Node<T>>>,
}
impl<T: Ord> Tree<T> {
/// Creates an empty tree
pub fn new() -> Self {
Tree { root: None }
}
pub fn inorder(&self) -> Vec<&T> {
self.root.as_ref().map(|n| n.inorder()).unwrap() // how to pass result ?
}
}
impl<T: Ord> Node<T> {
pub fn inorder(&self) -> Vec<&T> {
let mut result: Vec<&T> = Vec::new();
match *self {
None => return result,
Some(ref node) => {
let left_vec = node.left.inorder();
result.extend(left_vec);
result.extend(node.value);
let right_vec = node.right.inorder();
result.extend(right_vec);
}
}
}
}
This is the error report:
error[E0308]: mismatched types
--> src/main.rs:27:13
|
27 | None => return result,
| ^^^^ expected struct `Node`, found enum `std::option::Option`
|
= note: expected type `Node<T>`
= note: found type `std::option::Option<_>`
error[E0308]: mismatched types
--> src/main.rs:29:13
|
29 | Some(ref node) => {
| ^^^^^^^^^^^^^^ expected struct `Node`, found enum `std::option::Option`
|
= note: expected type `Node<T>`
= note: found type `std::option::Option<_>`
In Node::inorder
, I want to return a empty vector if a node does not exist; if the node does exist, I want to grow the vector inorder and recur.
The match
doesn't work between a Node
and Option
, but I am not sure how to bridge between them.