mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
102 in rust
This commit is contained in:
@ -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.二叉树的右视图
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)
|
||||
|
Reference in New Issue
Block a user