Skip to content

Commit 3432299

Browse files
authored
leetcode-study (#2631)
1 parent 3f27e99 commit 3432299

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// TC: O(n)
2+
// SC: O(n)
3+
use std::cell::RefCell;
4+
use std::collections::VecDeque;
5+
use std::rc::Rc;
6+
7+
impl Solution {
8+
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
9+
let mut output = Vec::new();
10+
let mut queue = VecDeque::new();
11+
if let Some(node) = root {
12+
queue.push_back(node);
13+
}
14+
while !queue.is_empty() {
15+
let mut values = Vec::with_capacity(queue.len());
16+
for _ in 0..queue.len() {
17+
let node = queue.pop_front().unwrap();
18+
let node = node.borrow();
19+
values.push(node.val);
20+
if let Some(left) = node.left.clone() {
21+
queue.push_back(left);
22+
}
23+
if let Some(right) = node.right.clone() {
24+
queue.push_back(right);
25+
}
26+
}
27+
output.push(values);
28+
}
29+
output
30+
}
31+
}

0 commit comments

Comments
 (0)