I am trying to update a node of a tree structure. A node which is to be updated is selected randomly. To sample a node in the tree using the Reservoir Sampling algorithm, I have to iterate over the nodes, so I have tried to make an Iterator
for my Node
enum.
The problem is that, on the one hand, I have to store references for child nodes in a stack or queue, however on the other hand, I have to return a mutable reference for a parent node. Rust does not allow to make multiple mutable references for one value, neither to convert an immutable reference into a mutable reference.
Is there a way to iterate over a mutable tree? Or is there another approach to randomly get a mutable reference to a node in a tree?
Here is my code.
#![feature(box_syntax, box_patterns)]
extern crate rand;
// Simple binary tree structure
#[derive(Debug)]
enum Node {
Leaf(u8),
Branch(Box<Node>, Box<Node>),
}
impl Node {
fn iter_mut(&mut self) -> IterMut {
IterMut {
stack: vec![self],
}
}
fn pick_random_node_mut<'a>(&'a mut self) -> &'a mut Node {
// Revervoir sampling
let rng = &mut rand::thread_rng();
rand::seq::sample_iter(rng, self.iter_mut(), 1)
.ok().and_then(|mut v| v.pop()).unwrap()
}
}
// An iterator for `Node`
struct IterMut<'a> {
stack: Vec<&'a mut Node>,
}
impl <'a> Iterator for IterMut<'a> {
type Item = &'a mut Node;
fn next(&mut self) -> Option<&'a mut Node> {
let node = self.stack.pop()?;
// I am stucking here: cannot borrow `*node` as mutable more than once at a time
if let &mut Node::Branch(box ref mut a, box ref mut b) = node {
self.stack.push(b);
self.stack.push(a);
}
Some(node)
}
}
fn main() {
use Node::*;
let mut tree: Node = Branch(box Leaf(1), box Leaf(2));
println!("{:?}", tree);
{
let node: &mut Node = tree.pick_random_node_mut();
*node = Leaf(3);
}
println!("{:?}", tree);
}