mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1752 from Jack-Zhang-1314/patch-11
Update 0226.翻转二叉树.md about rust
This commit is contained in:
@ -857,6 +857,36 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
//* 递归 */
|
||||||
|
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
if let Some(node) = root.as_ref() {
|
||||||
|
let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone());
|
||||||
|
node.borrow_mut().left = Self::invert_tree(right);
|
||||||
|
node.borrow_mut().right = Self::invert_tree(left);
|
||||||
|
}
|
||||||
|
root
|
||||||
|
}
|
||||||
|
//* 迭代 */
|
||||||
|
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
let mut stack = vec![root.clone()];
|
||||||
|
while !stack.is_empty() {
|
||||||
|
if let Some(node) = stack.pop().unwrap() {
|
||||||
|
let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone());
|
||||||
|
stack.push(right.clone());
|
||||||
|
stack.push(left.clone());
|
||||||
|
node.borrow_mut().left = right;
|
||||||
|
node.borrow_mut().right = left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<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