mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1753 from Jack-Zhang-1314/patch-12
Update 0101.对称二叉树.md about rust
This commit is contained in:
@ -826,6 +826,67 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Rust
|
||||||
|
|
||||||
|
递归:
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
|
||||||
|
Self::recur(
|
||||||
|
&root.as_ref().unwrap().borrow().left,
|
||||||
|
&root.as_ref().unwrap().borrow().right,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
pub fn recur(
|
||||||
|
left: &Option<Rc<RefCell<TreeNode>>>,
|
||||||
|
right: &Option<Rc<RefCell<TreeNode>>>,
|
||||||
|
) -> bool {
|
||||||
|
match (left, right) {
|
||||||
|
(None, None) => true,
|
||||||
|
(Some(n1), Some(n2)) => {
|
||||||
|
return n1.borrow().val == n2.borrow().val
|
||||||
|
&& Self::recur(&n1.borrow().left, &n2.borrow().right)
|
||||||
|
&& Self::recur(&n1.borrow().right, &n2.borrow().left)
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
迭代:
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
|
||||||
|
let mut queue = VecDeque::new();
|
||||||
|
if let Some(node) = root {
|
||||||
|
queue.push_back(node.borrow().left.clone());
|
||||||
|
queue.push_back(node.borrow().right.clone());
|
||||||
|
}
|
||||||
|
while !queue.is_empty() {
|
||||||
|
let (n1, n2) = (queue.pop_front().unwrap(), queue.pop_front().unwrap());
|
||||||
|
match (n1.clone(), n2.clone()) {
|
||||||
|
(None, None) => continue,
|
||||||
|
(Some(n1), Some(n2)) => {
|
||||||
|
if n1.borrow().val != n2.borrow().val {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return false,
|
||||||
|
};
|
||||||
|
queue.push_back(n1.as_ref().unwrap().borrow().left.clone());
|
||||||
|
queue.push_back(n2.as_ref().unwrap().borrow().right.clone());
|
||||||
|
queue.push_back(n1.unwrap().borrow().right.clone());
|
||||||
|
queue.push_back(n2.unwrap().borrow().left.clone());
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<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