From c64c013b9b157b99ac6a87308a2e4352abbd989f Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 5 Nov 2022 16:24:41 +0800 Subject: [PATCH] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 03304caf..78861040 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -525,6 +525,46 @@ object Solution { } } ``` + +rust: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn preorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + Self::traverse(&root, &mut res); + res + } + +//前序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + res.push(node.borrow().val); + Self::traverse(&node.borrow().left, res); + Self::traverse(&node.borrow().right, res); + } + } +//后序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + Self::traverse(&node.borrow().left, res); + Self::traverse(&node.borrow().right, res); + res.push(node.borrow().val); + } + } +//中序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + Self::traverse(&node.borrow().left, res); + res.push(node.borrow().val); + Self::traverse(&node.borrow().right, res); + } + } +} +``` +