mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1801 from fwqaaq/patch-10
Update 0701.二叉搜索树中的插入操作.md about rust
This commit is contained in:
@ -645,6 +645,66 @@ 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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
递归:
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn insert_into_bst(
|
||||
root: Option<Rc<RefCell<TreeNode>>>,
|
||||
val: i32,
|
||||
) -> Option<Rc<RefCell<TreeNode>>> {
|
||||
if let Some(node) = &root {
|
||||
if node.borrow().val > val {
|
||||
let left = Self::insert_into_bst(node.borrow_mut().left.take(), val);
|
||||
node.borrow_mut().left = left;
|
||||
} else {
|
||||
let right = Self::insert_into_bst(node.borrow_mut().right.take(), val);
|
||||
node.borrow_mut().right = right;
|
||||
}
|
||||
root
|
||||
} else {
|
||||
Some(Rc::new(RefCell::new(TreeNode::new(val))))
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user