From 7c97e9b7d29345e12d16bd34e04233bc78e16ff8 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 17:43:14 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0=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/0101.对称二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 30ca3d77..6c96f1db 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -772,6 +772,34 @@ object Solution { } ``` +## Rust + +递归: +```rust +impl Solution { + pub fn is_symmetric(root: Option>>) -> bool { + Self::recur( + &root.as_ref().unwrap().borrow().left, + &root.as_ref().unwrap().borrow().right, + ) + } + pub fn recur( + left: &Option>>, + right: &Option>>, + ) -> 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, + } + } +} +``` +

From 30a7d36699fcf7f7ffada9b3381553c7e3924873 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 18:36:39 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0=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/0101.对称二叉树.md | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 6c96f1db..841dbec3 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -800,6 +800,39 @@ impl Solution { } ``` +迭代: +```rust +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +impl Solution { + pub fn is_symmetric(root: Option>>) -> 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 + } +} +``` +