From 1c369bb83631f4449af7e646bc26bc86aacc5442 Mon Sep 17 00:00:00 2001 From: 3Xpl0it3r Date: Sat, 14 May 2022 23:24:57 +0800 Subject: [PATCH] 102 in rust --- problems/0102.二叉树的层序遍历.md | 59 +++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ab8f2e57..13267819 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -299,6 +299,36 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] { } ``` +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()); + } + } + ans.push(level); + } + ans +} +``` + + **此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!** @@ -528,6 +558,35 @@ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { } ``` +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()); + } + } + ans.push(level); + } + ans +} +``` + # 199.二叉树的右视图 [力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)