struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn new(value: i32) -> Self {
Node { value, left: None, right: None }
}
fn insert(&mut self, val: i32) {
if val < self.value {
match self.left {
Some(ref mut left_node) => left_node.insert(val),
None => self.left = Some(Box::new(Node::new(val))),
}
} else {
match self.right {
Some(ref mut right_node) => right_node.insert(val),
None => self.right = Some(Box::new(Node::new(val))),
}
}
}
fn print_in_order(&self) {
if let Some(ref left) = self.left {
left.print_in_order();
}
print!("{} -> ", self.value);
if let Some(ref right) = self.right {
right.print_in_order();
}
}
}
fn main() {
let mut root = Node::new(10);
root.insert(5);
root.insert(15);
root.insert(3);
root.insert(7);
root.print_in_order();
}The insert method places smaller values to the left and larger or equal values to the right. In-order traversal visits left subtree, node, then right subtree, resulting in sorted order.
Trees naturally represent hierarchical data with nodes having multiple children, which arrays and linked lists cannot do efficiently because they are linear structures.
fn search(node: &Option<Box<Node>>, val: i32) -> bool { if let Some(ref n) = node { if n.value == val { return true; } else if val < n.value { search(&n.left, val) } else { search(&n.right, val) } } else { false } }
The function does not return false when the node is None, so the else branch is missing a return value, causing a compilation error.
A hash map provides O(1) lookup by employee ID, and storing tree nodes as values maintains the hierarchy, combining both needs efficiently.
Hierarchical data involves nodes with multiple children. Arrays and linked lists are linear and do not support multiple branches naturally, making trees the ideal structure.
