Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c369bb

Browse files
102 in rust
1 parent 6de51d2 commit 1c369bb

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

‎problems/0102.二叉树的层序遍历.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,36 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] {
299299
}
300300
```
301301

302+
Rust:
303+
304+
```rust
305+
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
306+
let mut ans = Vec::new();
307+
let mut stack = Vec::new();
308+
if root.is_none(){
309+
return ans;
310+
}
311+
stack.push(root.unwrap());
312+
while stack.is_empty()!= true{
313+
let num = stack.len();
314+
let mut level = Vec::new();
315+
for _i in 0..num{
316+
let tmp = stack.remove(0);
317+
level.push(tmp.borrow_mut().val);
318+
if tmp.borrow_mut().left.is_some(){
319+
stack.push(tmp.borrow_mut().left.take().unwrap());
320+
}
321+
if tmp.borrow_mut().right.is_some(){
322+
stack.push(tmp.borrow_mut().right.take().unwrap());
323+
}
324+
}
325+
ans.push(level);
326+
}
327+
ans
328+
}
329+
```
330+
331+
302332
**此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!**
303333

304334

@@ -528,6 +558,35 @@ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
528558
}
529559
```
530560

561+
Rust:
562+
563+
```rust
564+
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
565+
let mut ans = Vec::new();
566+
let mut stack = Vec::new();
567+
if root.is_none(){
568+
return ans;
569+
}
570+
stack.push(root.unwrap());
571+
while stack.is_empty()!= true{
572+
let num = stack.len();
573+
let mut level = Vec::new();
574+
for _i in 0..num{
575+
let tmp = stack.remove(0);
576+
level.push(tmp.borrow_mut().val);
577+
if tmp.borrow_mut().left.is_some(){
578+
stack.push(tmp.borrow_mut().left.take().unwrap());
579+
}
580+
if tmp.borrow_mut().right.is_some(){
581+
stack.push(tmp.borrow_mut().right.take().unwrap());
582+
}
583+
}
584+
ans.push(level);
585+
}
586+
ans
587+
}
588+
```
589+
531590
# 199.二叉树的右视图
532591

533592
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /