Skip to content

Commit 5534454

Browse files
committed
q199
1 parent 842796a commit 5534454

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

src/tree/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,4 +136,5 @@ macro_rules! tree {
136136
mod q108;
137137
mod q95;
138138
mod q129;
139-
mod q1382;
139+
mod q1382;
140+
mod q199;

src/tree/q199.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/// Given 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.
2+
///
3+
/// Example:
4+
///
5+
/// Input: [1,2,3,null,5,null,4]
6+
/// Output: [1, 3, 4]
7+
/// Explanation:
8+
///
9+
/// 1 <---
10+
/// / \
11+
/// 2 3 <---
12+
/// \ \
13+
/// 5 4 <---
14+
///
15+
/// 来源:力扣(LeetCode)
16+
/// 链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
17+
/// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
18+
use super::*;
19+
use std::collections::VecDeque;
20+
21+
struct Solution ();
22+
impl Solution {
23+
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
24+
25+
let mut result = vec![];
26+
let mut queue = VecDeque::new();
27+
28+
if root.is_some() {
29+
queue.push_front((root.unwrap(), 1))
30+
}
31+
32+
let mut last_lvl = 0;
33+
34+
while !queue.is_empty() {
35+
let (r, lvl) = queue.pop_back().unwrap();
36+
37+
38+
let rr = RefCell::borrow(&r);
39+
40+
if lvl != last_lvl {
41+
last_lvl = lvl;
42+
result.push(rr.val);
43+
}
44+
if let Some(r) = &rr.right {
45+
queue.push_front((Rc::clone(r), lvl + 1))
46+
}
47+
if let Some(l) = &rr.left {
48+
queue.push_front((Rc::clone(l), lvl + 1))
49+
}
50+
}
51+
result
52+
53+
}
54+
55+
}
56+
57+
58+
#[cfg(test)]
59+
mod tests {
60+
use super::*;
61+
62+
#[test]
63+
fn test_1() {
64+
let t = tree!(1,2,3,null,5,null,4);
65+
println!("{:?}", Solution::right_side_view(t));
66+
}
67+
68+
}

0 commit comments

Comments
 (0)