diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 9c34ce20..3136c0be 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -857,6 +857,36 @@ object Solution { } ``` +### rust + +```rust +impl Solution { + //* 递归 */ + pub fn invert_tree(root: Option>>) -> Option>> { + 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>>) -> Option>> { + 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 + } +} +``` +