From 3f70c16fa6bbb059cd7e102b791d25b844bafd74 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 01:29:42 +0800 Subject: [PATCH] =?UTF-8?q?update=200102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md=20about=20usin?= =?UTF-8?q?g=20vecdeque=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 45 ++++++++++++----------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 3a4e0a31..f4f51f01 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -380,29 +380,32 @@ object Solution { Rust: ```rust -pub fn level_order(root: Option>>) -> Vec> { - let mut ans = Vec::new(); - let mut stack = Vec::new(); - if root.is_none(){ - return ans; - } - stack.push(root.unwrap()); - while stack.is_empty()!= true{ - let num = stack.len(); - let mut level = Vec::new(); - for _i in 0..num{ - let tmp = stack.remove(0); - level.push(tmp.borrow_mut().val); - if tmp.borrow_mut().left.is_some(){ - stack.push(tmp.borrow_mut().left.take().unwrap()); - } - if tmp.borrow_mut().right.is_some(){ - stack.push(tmp.borrow_mut().right.take().unwrap()); - } +use std::cell::RefCell; +use std::rc::Rc; +use std::collections::VecDeque; +impl Solution { + pub fn level_order(root: Option>>) -> Vec> { + let mut res = vec![]; + let mut queue = VecDeque::new(); + if root.is_some() { + queue.push_back(root); } - ans.push(level); + while !queue.is_empty() { + let mut temp = vec![]; + for _ in 0..queue.len() { + let node = queue.pop_front().unwrap().unwrap(); + temp.push(node.borrow().val); + if node.borrow().left.is_some() { + queue.push_back(node.borrow().left.clone()); + } + if node.borrow().right.is_some() { + queue.push_back(node.borrow().right.clone()); + } + } + res.push(temp); + } + res } - ans } ```