I'll help you implement a generic tree data structure in Rust where each node can have multiple children. Here's an implementation with basic operations:
use std::collections::VecDeque;
#[derive(Debug)]
struct Tree<T> {
root: Option<Node<T>>,
}
#[derive(Debug)]
struct Node<T> {
value: T,
children: Vec<Node<T>>,
}
impl<T> Tree<T> {
fn new() -> Self {
Tree { root: None }
}
fn with_root(value: T) -> Self {
Tree {
root: Some(Node {
value,
children: Vec::new(),
}),
}
}
}
impl<T> Node<T> {
fn new(value: T) -> Self {
Node {
value,
children: Vec::new(),
}
}
fn add_child(&mut self, value: T) -> &mut Node<T> {
let child = Node::new(value);
self.children.push(child);
self.children.last_mut().unwrap()
}
// Depth-first search
fn traverse(&self, f: &mut impl FnMut(&T)) {
f(&self.value);
for child in &self.children {
child.traverse(f);
}
}
// Breadth-first search
fn traverse_bfs(&self, f: &mut impl FnMut(&T)) {
let mut queue = VecDeque::new();
queue.push_back(self);
while let Some(node) = queue.pop_front() {
f(&node.value);
for child in &node.children {
queue.push_back(child);
}
}
}
}
// Example usage
fn main() {
let mut tree = Tree::with_root(1);
if let Some(root) = &mut tree.root {
let child1 = root.add_child(2);
child1.add_child(4);
child1.add_child(5);
let child2 = root.add_child(3);
child2.add_child(6);
println!("DFS traversal:");
root.traverse(&mut |value| print!("{} ", value));
println!("\n");
println!("BFS traversal:");
root.traverse_bfs(&mut |value| print!("{} ", value));
println!();
}
}
This implementation includes:
- A generic
Tree struct that holds an optional root node
- A generic
Node struct that contains a value and a vector of children
- Basic operations:
- Creating an empty tree
- Creating a tree with a root node
- Adding children to nodes
- Depth-first traversal
- Breadth-first traversal
The tree is generic over type T, so it can store any type of data. The example usage creates a simple numeric tree and demonstrates both DFS and BFS traversals.
Would you like me to add any additional functionality, such as:
- Finding nodes by value
- Removing nodes
- Tree balancing
- Serialization
- Iterator implementation