/
recursive.rs
51 lines (38 loc) · 1.38 KB
/
recursive.rs
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use crate::data_structures::TreeNode;
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn right_side_view_helper(root: Option<Rc<RefCell<TreeNode>>>, depth: usize, result: &mut Vec<i32>) {
if let Some(node) = root {
let (left, right, next_depth) = {
let node = node.borrow();
if depth == result.len() {
result.push(node.val);
}
(node.left.clone(), node.right.clone(), depth + 1)
};
Self::right_side_view_helper(right, next_depth, result);
Self::right_side_view_helper(left, next_depth, result);
}
}
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
Self::right_side_view_helper(root, 0, &mut result);
result
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
Self::right_side_view(root)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}