mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
Update 0235.二叉搜索树的最近公共祖先.md
This commit is contained in:
@ -418,6 +418,39 @@ object Solution {
|
||||
}
|
||||
```
|
||||
|
||||
## rust
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn lowest_common_ancestor(
|
||||
root: Option<Rc<RefCell<TreeNode>>>,
|
||||
p: Option<Rc<RefCell<TreeNode>>>,
|
||||
q: Option<Rc<RefCell<TreeNode>>>,
|
||||
) -> Option<Rc<RefCell<TreeNode>>> {
|
||||
let q_val = q.as_ref().unwrap().borrow().val;
|
||||
let p_val = p.as_ref().unwrap().borrow().val;
|
||||
let root_val = root.as_ref().unwrap().borrow().val;
|
||||
|
||||
if root_val > q_val && root_val > p_val {
|
||||
return Self::lowest_common_ancestor(
|
||||
root.as_ref().unwrap().borrow().left.clone(),
|
||||
p,
|
||||
q,
|
||||
);
|
||||
};
|
||||
|
||||
if root_val < q_val && root_val < p_val {
|
||||
return Self::lowest_common_ancestor(
|
||||
root.as_ref().unwrap().borrow().right.clone(),
|
||||
p,
|
||||
q,
|
||||
);
|
||||
}
|
||||
root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user