mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
Update 0235.二叉搜索树的最近公共祖先.md
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user