I wrote this code for the leetcode same tree problem:
use std::cell::RefCell;
use std::rc::Rc;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
struct Solution;
impl Solution {
pub fn is_same_tree(
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
match (p, q) {
(None, None) => true,
(Some(p), Some(q)) if p.borrow().val == q.borrow().val => {
// this line won't work, it will cause BorrowMutError at runtime
// but the `a & b` version works
return (Self::is_same_tree(
p.borrow_mut().left.take(),
q.borrow_mut().left.take(),
)) && (Self::is_same_tree(
p.borrow_mut().right.take(),
q.borrow_mut().right.take(),
));
let a = Self::is_same_tree(p.borrow_mut().left.take(), q.borrow_mut().left.take());
let b =
Self::is_same_tree(p.borrow_mut().right.take(), q.borrow_mut().right.take());
a && b
}
_ => false,
}
}
}
fn main() {
let p = Some(Rc::new(RefCell::new(TreeNode {
val: 1,
left: Some(Rc::new(RefCell::new(TreeNode::new(2)))),
right: Some(Rc::new(RefCell::new(TreeNode::new(3)))),
})));
let q = Some(Rc::new(RefCell::new(TreeNode {
val: 1,
left: Some(Rc::new(RefCell::new(TreeNode::new(2)))),
right: Some(Rc::new(RefCell::new(TreeNode::new(3)))),
})));
println!("{:?}", Solution::is_same_tree(p, q));
}
thread 'main' panicked at 'already borrowed: BorrowMutError', src/main.rs:39:23
I think &&
is a short-circuit operator which means the two expressions won't exist at the same time, so two mutable references should not exist at the same time.