Merge pull request #1807 from fwqaaq/patch-11

Update 0450.删除二叉搜索树中的节点.md
This commit is contained in:
程序员Carl
2023-05-24 09:26:08 +08:00
committed by GitHub

View File

@ -680,6 +680,40 @@ object Solution {
} }
``` ```
## rust
```rust
impl Solution {
pub fn delete_node(
root: Option<Rc<RefCell<TreeNode>>>,
key: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
root.as_ref()?;
let mut node = root.as_ref().unwrap().borrow_mut();
match node.val.cmp(&key) {
std::cmp::Ordering::Less => node.right = Self::delete_node(node.right.clone(), key),
std::cmp::Ordering::Equal => match (node.left.clone(), node.right.clone()) {
(None, None) => return None,
(None, Some(r)) => return Some(r),
(Some(l), None) => return Some(l),
(Some(l), Some(r)) => {
let mut cur = Some(r.clone());
while let Some(n) = cur.clone().unwrap().borrow().left.clone() {
cur = Some(n);
}
cur.unwrap().borrow_mut().left = Some(l);
return Some(r);
}
},
std::cmp::Ordering::Greater => node.left = Self::delete_node(node.left.clone(), key),
}
drop(node);
root
}
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>