-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree_right_side_view.rs
87 lines (74 loc) · 2.33 KB
/
binary_tree_right_side_view.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use crate::tree_node::TreeNode;
use crate::tree_node_additions::TreeNodeAdditions;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
/// Given the `root` of a binary tree, imagine yourself standing on the right
/// side of it, return the values of the nodes you can see ordered from top
/// to bottom.
struct Solution;
impl Solution {
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
if root.is_none() {
vec![]
} else {
let mut result = Vec::new();
let mut queue = VecDeque::new();
queue.push_back(root.clone());
while !queue.is_empty() {
let len = queue.len();
let right_side = queue.back().unwrap();
right_side.get_value().map(|v| {
result.push(v);
v
});
for _ in 0..len {
let item = queue.pop_front().unwrap();
match item {
Some(rc) => {
let node = rc.borrow();
if node.left.is_some() {
queue.push_back(node.left.clone());
}
if node.right.is_some() {
queue.push_back(node.right.clone());
}
}
None => {
// do nothing
}
}
}
}
result
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let root = tree!("[1,2,3,null,5,null,4]");
let result = Solution::right_side_view(root);
assert_eq!(result, vec![1, 3, 4]);
}
#[test]
fn example_2() {
let root = tree!("[1,null,3]");
let result = Solution::right_side_view(root);
assert_eq!(result, vec![1, 3]);
}
#[test]
fn example_3() {
let root = tree!("[]");
let result = Solution::right_side_view(root);
assert_eq!(result, vec![]);
}
#[test]
fn example_4() {
let root = tree!("[1,2]");
let result = Solution::right_side_view(root);
assert_eq!(result, vec![1, 2]);
}
}