MCPcopy Create free account
hub / github.com/douchuan/algorithm / delete

Function delete

src/tree/binary/bst.rs:207–258  ·  view source on GitHub ↗

# Safety This is highly unsafe, due to pointer 从二叉搜索树中删除节点 x 的方法如下: 如果 x 没有子节点,或者只有一个孩子,直接将 x“切下”; 否则,x 有两个孩子,我们用其右子树中的最小值替换掉 x,然后将右子树中的这一最小值“切掉”。

(
    mut root: Option<NonNull<Node<K, V>>>,
    mut x: Option<NonNull<Node<K, V>>>,
)

Source from the content-addressed store, hash-verified

205/// 如果 x 没有子节点,或者只有一个孩子,直接将 x“切下”;
206/// 否则,x 有两个孩子,我们用其右子树中的最小值替换掉 x,然后将右子树中的这一最小值“切掉”。
207unsafe fn delete<K, V>(
208 mut root: Option<NonNull<Node<K, V>>>,
209 mut x: Option<NonNull<Node<K, V>>>,
210) -> Option<NonNull<Node<K, V>>>
211where
212 K: Ord,
213{
214 if let Some(mut px) = x {
215 let old_x = x;
216 let parent = px.as_ref().parent;
217
218 if px.as_ref().left.is_none() {
219 x = px.as_ref().right;
220 } else if px.as_ref().right.is_none() {
221 x = px.as_ref().left;
222 } else {
223 let min = find_min(px.as_ref().right).unwrap();
224 NodeQuery::new(x).copy_entry(min);
225 let min_parent = min.as_ref().parent;
226 if min_parent != x {
227 let min_right = min.as_ref().right;
228 min_parent.unwrap().as_mut().left = min_right;
229 } else {
230 px.as_mut().right = min.as_ref().right;
231 }
232 if let Some(mut min_right) = min.as_ref().right {
233 let min_parent = min.as_ref().parent;
234 min_right.as_mut().parent = min_parent;
235 }
236 Node::release(min);
237 return root;
238 }
239
240 if let Some(mut px) = x {
241 px.as_mut().parent = parent;
242 }
243
244 if let Some(mut parent) = parent {
245 if parent.as_ref().left == old_x {
246 parent.as_mut().left = x;
247 } else {
248 parent.as_mut().right = x;
249 }
250 } else {
251 root = x;
252 }
253
254 Node::release(old_x.unwrap());
255 }
256
257 root
258}
259
260/// is the tree rooted at x a BST with all keys strictly between min and max
261/// (if min or max is null, treat as empty constraint)

Callers 1

deleteMethod · 0.70

Calls 3

find_minFunction · 0.85
is_noneMethod · 0.80
copy_entryMethod · 0.80

Tested by

no test coverage detected