diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index f40f778a..675a0e4a 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -414,6 +414,56 @@ object Solution { } ``` +### rust + +递归: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn search_bst( + root: Option>>, + val: i32, + ) -> Option>> { + 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>>, + val: i32, + ) -> Option>> { + 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 + } +} +``` +