#199
Medium Algorithms Binary tree right side view
Tree Depth-First Search Breadth-First Search Binary Tree
69.6% acceptance
Feb 27, 2026
13351
1086
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.
Solution
Rust
Time O(n²)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
let mut queue = std::collections::VecDeque::new();
if let Some(node) = root {
queue.push_back(node);
}
while !queue.is_empty() {
let level_size = queue.len();
for i in 0..level_size {
if let Some(node) = queue.pop_front() {
let node = node.borrow();
if i == level_size - 1 {
result.push(node.val);
}
if let Some(left) = node.left.clone() {
queue.push_back(left);
}
if let Some(right) = node.right.clone() {
queue.push_back(right);
}
}
}
}
result
}
}