Update 0236.二叉树的最近公共祖先.md

This commit is contained in:
fw_qaq
2022-12-04 16:49:13 +08:00
committed by GitHub
parent e7f3d8dd29
commit f056b7ece6

View File

@ -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"/>