From 9d0872312c211f877e7af9dc2e76302961fd46af Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 16:16:48 +0800 Subject: [PATCH] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) 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 + } +} +``` +