Skip to content

Commit bd4a3a2

Browse files
committed
feat(trees): add 102_binary_tree_level_order_traversal.rs
1 parent 5c0c771 commit bd4a3a2

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,4 @@ so that you can use `just tf TEST` command to test.
138138
| - | - | - |
139139
| 226. Invert Binary Tree | Easy | [226_invert_binary_tree.rs](./tests/226_invert_binary_tree.rs) |
140140
| 104. Maximum Depth of Binary Tree | Easy | [104_maximum_depth_of_binary_tree.rs](./tests/104_maximum_depth_of_binary_tree.rs) |
141+
| 102. Binary Tree Level Order Traversal | Medium | [102_binary_tree_level_order_traversal.rs](./tests/102_binary_tree_level_order_traversal.rs) |
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 102. Binary Tree Level Order Traversal
2+
// https://leetcode.com/problems/binary-tree-level-order-traversal/description/
3+
// Topics: Trees.
4+
// Difficulty: Medium.
5+
6+
#[test]
7+
fn test_102_binary_tree_level_order_traversal() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// Definition for a binary tree node.
13+
#[derive(Debug, PartialEq, Eq)]
14+
pub struct TreeNode {
15+
pub val: i32,
16+
pub left: Option<Rc<RefCell<TreeNode>>>,
17+
pub right: Option<Rc<RefCell<TreeNode>>>,
18+
}
19+
20+
impl TreeNode {
21+
#[inline]
22+
pub fn new(val: i32) -> Self {
23+
TreeNode {
24+
val,
25+
left: None,
26+
right: None,
27+
}
28+
}
29+
}
30+
31+
// ---------------------------------
32+
// copy to leetcode starts from here
33+
// ---------------------------------
34+
35+
use std::cell::RefCell;
36+
use std::collections::VecDeque;
37+
use std::rc::Rc;
38+
39+
impl Solution {
40+
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
41+
let mut result: Vec<Vec<i32>> = vec![];
42+
let mut vd = VecDeque::new();
43+
if let Some(r) = root {
44+
vd.push_back(r);
45+
}
46+
while !vd.is_empty() {
47+
let mut row: Vec<i32> = vec![];
48+
for _ in 0..vd.len() {
49+
// `vd` is not empty, thus `unwrap()` is fine here.
50+
let node = vd.pop_front().unwrap();
51+
row.push(node.borrow().val);
52+
if let Some(left) = node.borrow_mut().left.take() {
53+
vd.push_back(left);
54+
}
55+
if let Some(right) = node.borrow_mut().right.take() {
56+
vd.push_back(right);
57+
}
58+
}
59+
result.push(row);
60+
}
61+
result
62+
}
63+
}

0 commit comments

Comments
 (0)