mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
update 0102.二叉树的层序遍历.md about using vecdeque rust
This commit is contained in:
@ -380,29 +380,32 @@ object Solution {
|
||||
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>> {
|
||||
let mut ans = Vec::new();
|
||||
let mut stack = Vec::new();
|
||||
if root.is_none(){
|
||||
return ans;
|
||||
let mut res = vec![];
|
||||
let mut queue = VecDeque::new();
|
||||
if root.is_some() {
|
||||
queue.push_back(root);
|
||||
}
|
||||
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());
|
||||
while !queue.is_empty() {
|
||||
let mut temp = vec![];
|
||||
for _ in 0..queue.len() {
|
||||
let node = queue.pop_front().unwrap().unwrap();
|
||||
temp.push(node.borrow().val);
|
||||
if node.borrow().left.is_some() {
|
||||
queue.push_back(node.borrow().left.clone());
|
||||
}
|
||||
if tmp.borrow_mut().right.is_some(){
|
||||
stack.push(tmp.borrow_mut().right.take().unwrap());
|
||||
if node.borrow().right.is_some() {
|
||||
queue.push_back(node.borrow().right.clone());
|
||||
}
|
||||
}
|
||||
ans.push(level);
|
||||
res.push(temp);
|
||||
}
|
||||
res
|
||||
}
|
||||
ans
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user