mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1779 from fwqaaq/patch-4
Update 0700.二叉搜索树中的搜索.md about rust
This commit is contained in:
@ -414,6 +414,56 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### rust
|
||||||
|
|
||||||
|
递归:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn search_bst(
|
||||||
|
root: Option<Rc<RefCell<TreeNode>>>,
|
||||||
|
val: i32,
|
||||||
|
) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
if root.is_none() || root.as_ref().unwrap().borrow().val == val {
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
let node_val = root.as_ref().unwrap().borrow().val;
|
||||||
|
if node_val > val {
|
||||||
|
return Self::search_bst(root.as_ref().unwrap().borrow().left.clone(), val);
|
||||||
|
}
|
||||||
|
if node_val < val {
|
||||||
|
return Self::search_bst(root.unwrap().borrow().right.clone(), val);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
迭代:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::cmp;
|
||||||
|
impl Solution {
|
||||||
|
pub fn search_bst(
|
||||||
|
mut root: Option<Rc<RefCell<TreeNode>>>,
|
||||||
|
val: i32,
|
||||||
|
) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
while let Some(ref node) = root.clone() {
|
||||||
|
match val.cmp(&node.borrow().val) {
|
||||||
|
cmp::Ordering::Less => root = node.borrow().left.clone(),
|
||||||
|
cmp::Ordering::Equal => return root,
|
||||||
|
cmp::Ordering::Greater => root = node.borrow().right.clone(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<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"/>
|
||||||
|
Reference in New Issue
Block a user