Skip to content

Commit 39aa91f

Browse files
committed
refactor: remove unnecessary borrows
1 parent 1c43d21 commit 39aa91f

1 file changed

Lines changed: 6 additions & 13 deletions

File tree

codes/rust/chapter_tree/binary_search_tree.rs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -111,29 +111,22 @@ impl BinarySearchTree {
111111
}
112112
// 若无待删除节点,则直接返回
113113
let Some(cur) = cur else { return };
114-
let borrow_cur = cur.borrow();
115-
let left_child = borrow_cur.left.as_ref();
116-
let right_child = borrow_cur.right.as_ref();
114+
let borrow = cur.borrow();
115+
let left_child = borrow.left.as_ref();
116+
let right_child = borrow.right.as_ref();
117117
// 当子节点的数量为 0 或 1 时
118118
if left_child.is_none() || right_child.is_none() {
119119
// 此时 child 为空或 cur 的唯一子节点
120120
let child = left_child.or(right_child).cloned();
121121
let Some(pre) = pre else {
122-
// 若 pre 为空,则查找节点的第一轮循环里发生了 break,此时 cur 指向根节点,
122+
// 若 pre 为空,则查找节点的第一轮循环里发生了 break,
123123
// 此时待删除的节点为根节点,应重新指定根节点
124124
self.root = child;
125125
return;
126126
};
127-
// 由于二叉搜索树不允许有重复节点,可以直接做值的相等性检查
128-
// 来确定 cur 是 pre 的左子节点还是右子节点
129-
let borrow_pre = pre.borrow();
130-
if let Some(left) = &borrow_pre.left
131-
&& borrow_cur.val == left.borrow().val
132-
{
133-
drop(borrow_pre);
127+
if borrow.val < pre.borrow().val {
134128
pre.borrow_mut().left = child;
135129
} else {
136-
drop(borrow_pre);
137130
pre.borrow_mut().right = child;
138131
}
139132
}
@@ -156,7 +149,7 @@ impl BinarySearchTree {
156149
// 这是当前作用域内仍然存活的借用,需要在递归前丢弃,如果保留在调用栈中,
157150
// 可能会因同一节点的可变借用而触发 panic;即使没有发生这种情况,下面对
158151
// cur 节点的可变借用也会导致 panic
159-
drop(borrow_cur);
152+
drop(borrow);
160153
let tmp_val = tmp.borrow().val;
161154
// 递归删除节点 tmp
162155
self.remove(tmp_val);

0 commit comments

Comments
 (0)