Update 0701.二叉搜索树中的插入操作.md

This commit is contained in:
fw_qaq 2022-12-05 22:26:55 +08:00 committed by GitHub
parent 7477960034
commit 40db289357
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 36 additions and 0 deletions

View File

@ -641,6 +641,42 @@ object Solution {
}
```
### rust
迭代:
```rust
impl Solution {
pub fn insert_into_bst(
root: Option<Rc<RefCell<TreeNode>>>,
val: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
if root.is_none() {
return Some(Rc::new(RefCell::new(TreeNode::new(val))));
}
let mut cur = root.clone();
let mut pre = None;
while let Some(node) = cur.clone() {
pre = cur;
if node.borrow().val > val {
cur = node.borrow().left.clone();
} else {
cur = node.borrow().right.clone();
};
}
let r = Some(Rc::new(RefCell::new(TreeNode::new(val))));
let mut p = pre.as_ref().unwrap().borrow_mut();
if val < p.val {
p.left = r;
} else {
p.right = r;
}
root
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">