Update 0235.二叉搜索树的最近公共祖先.md

This commit is contained in:
fw_qaq
2022-12-04 19:35:20 +08:00
committed by GitHub
parent 3f7beb8c8f
commit 6866f2b9ac

View File

@ -420,6 +420,8 @@ object Solution {
## rust
递归:
```rust
impl Solution {
pub fn lowest_common_ancestor(
@ -451,6 +453,32 @@ impl Solution {
}
```
迭代:
```rust
impl Solution {
pub fn lowest_common_ancestor(
mut root: Option<Rc<RefCell<TreeNode>>>,
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
let p_val = p.unwrap().borrow().val;
let q_val = q.unwrap().borrow().val;
while let Some(node) = root.clone() {
let root_val = node.borrow().val;
if root_val > q_val && root_val > p_val {
root = node.borrow().left.clone();
} else if root_val < q_val && root_val < p_val {
root = node.borrow().right.clone();
} else {
return root;
}
}
None
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">