Update 0226.翻转二叉树.md

This commit is contained in:
fw_qaq
2022-11-13 16:16:48 +08:00
committed by GitHub
parent b56bc32a23
commit 9d0872312c

View File

@ -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">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>