forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0102-binary-tree-level-order-traversal.rs
More file actions
34 lines (29 loc) · 1.06 KB
/
0102-binary-tree-level-order-traversal.rs
File metadata and controls
34 lines (29 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
if let Some(root) = root {
let mut frontier : Vec<(Rc<RefCell<TreeNode>>, u16)> = vec![(root, 0)];
let mut res : Vec<Vec<i32>> = vec![];
let mut len : u16 = 0;
while let Some((node, depth)) = frontier.pop() {
let val = node.borrow().val;
if depth == len {
res.push(vec![val]);
len += 1;
} else {
res[depth as usize].push(val);
}
if let Some(right) = node.borrow_mut().right.take() {
frontier.push((right, depth + 1));
}
if let Some(left) = node.borrow_mut().left.take() {
frontier.push((left, depth + 1));
}
}
res
} else {
vec![]
}
}
}