mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #1796 from fwqaaq/patch-8
Update 0236.二叉树的最近公共祖先.md about rust
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">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user