mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0236.二叉树的最近公共祖先.md
This commit is contained in:
@ -384,6 +384,34 @@ 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>>> {
|
||||||
|
if root == p || root == q || root.is_none() {
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
let left = Self::lowest_common_ancestor(
|
||||||
|
root.as_ref().unwrap().borrow().left.clone(),
|
||||||
|
p.clone(),
|
||||||
|
q.clone(),
|
||||||
|
);
|
||||||
|
let right =
|
||||||
|
Self::lowest_common_ancestor(root.as_ref().unwrap().borrow().right.clone(), p, q);
|
||||||
|
match (&left, &right) {
|
||||||
|
(None, Some(_)) => right,
|
||||||
|
(Some(_), Some(_)) => root,
|
||||||
|
_ => left,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<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