102 in rust

This commit is contained in:
3Xpl0it3r
2022-05-14 23:24:57 +08:00
parent 6de51d29b8
commit 1c369bb836

View File

@ -299,6 +299,36 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] {
} }
``` ```
Rust:
```rust
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
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<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
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.二叉树的右视图 # 199.二叉树的右视图
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/) [力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)