我需要在树中找到具有最大值的节点,假设子节点的值总是大于拥有节点的值,然后修改它:
#[derive(Debug)]
struct Node {
val: usize,
nodes: Vec<Node>,
}
fn find_max(node: &mut Node, val: usize) -> Option<&mut Node> {
if node.val < val {
return None;
}
let mut max_val = node.val;
let mut max: Option<&mut Node> = Some(node);
for n in &mut node.nodes {
if let Some(m) = find_max(n, max_val) {
max_val = m.val;
max = Some(m);
}
}
max
}
fn main() {
let mut root = Node {
val: 1,
nodes: vec![
Node {
val: 2,
nodes: vec![],
},
Node {
val: 3,
nodes: vec![
Node {
val: 4,
nodes: vec![],
},
],
},
],
};
println!("{:?}", find_max(&mut root, 0));
}
借用检查器返回此错误:
error[E0499]: cannot borrow `node.nodes` as mutable more than once at a time
--> src/main.rs:13:19
|
12 | let mut max: Option<&mut Node> = Some(node);
| ---- first mutable borrow occurs here
13 | for n in &mut node.nodes {
| ^^^^^^^^^^ second mutable borrow occurs here
...
20 | }
| - first borrow ends here
如果我从 中删除mut
,find_max
它可以工作,但我不知道如何从find_max
.
重要的是它find_max
本身不会修改任何东西。它只是搜索合适的节点。