mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
update 0102.二叉树的层序遍历.md about using vecdeque rust
This commit is contained in:
@ -380,29 +380,32 @@ object Solution {
|
|||||||
Rust:
|
Rust:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
impl Solution {
|
||||||
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
|
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
|
||||||
let mut ans = Vec::new();
|
let mut res = vec![];
|
||||||
let mut stack = Vec::new();
|
let mut queue = VecDeque::new();
|
||||||
if root.is_none(){
|
if root.is_some() {
|
||||||
return ans;
|
queue.push_back(root);
|
||||||
}
|
}
|
||||||
stack.push(root.unwrap());
|
while !queue.is_empty() {
|
||||||
while stack.is_empty()!= true{
|
let mut temp = vec![];
|
||||||
let num = stack.len();
|
for _ in 0..queue.len() {
|
||||||
let mut level = Vec::new();
|
let node = queue.pop_front().unwrap().unwrap();
|
||||||
for _i in 0..num{
|
temp.push(node.borrow().val);
|
||||||
let tmp = stack.remove(0);
|
if node.borrow().left.is_some() {
|
||||||
level.push(tmp.borrow_mut().val);
|
queue.push_back(node.borrow().left.clone());
|
||||||
if tmp.borrow_mut().left.is_some(){
|
|
||||||
stack.push(tmp.borrow_mut().left.take().unwrap());
|
|
||||||
}
|
}
|
||||||
if tmp.borrow_mut().right.is_some(){
|
if node.borrow().right.is_some() {
|
||||||
stack.push(tmp.borrow_mut().right.take().unwrap());
|
queue.push_back(node.borrow().right.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ans.push(level);
|
res.push(temp);
|
||||||
|
}
|
||||||
|
res
|
||||||
}
|
}
|
||||||
ans
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user