Binary Tree Right Side View
Medium
Topics
Given the root of a binary tree, imagine standing on the right side. Return the values of the nodes you can see, ordered top to bottom.
Example 1
visible from the right
One node per level — the rightmost — so the answer has 3 entries.
Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
Example 2
visible from the right
Input: root = [1,null,3] Output: [1,3]
Constraints
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
From the right you only see the last node of each level. So a level-order BFS, keeping the rightmost node of each level, is exactly the right-side view.
Approach
- BFS level by level.
- For each level, the last node dequeued is the visible one — record it.
- Collect these across all levels.
Dry Run
tree 1 2 3 null 5 null 4
1
/ \
2 3
\ \
5 4
level [1] take the last, 1 res [1]
level [2, 3] take the last, 3 res [1, 3]
level [5, 4] take the last, 4 res [1, 3, 4]
answer 1 3 4
The right side view is "the last node of each level", not "keep going right from
the root". On this tree the two happen to agree, both giving 1 3 4, so it is worth
having a tree where they do not. On 1 2 3 4 -- a 4 hanging off 2's left -- the
view is 1 3 4, because 4 is the only node on level 3, while walking right from the
root stops at 1 3. The view is whatever is rightmost at each DEPTH, no matter
which parent it hangs from or which side of that parent it is on.
Take the first of each level instead and you get the left side view, 1 2 5. Same
loop, one index changed.
The level size must be snapshotted before the inner loop for the same reason as
plain level-order: read len(q) live and the boundary dissolves, because the
children appended for the next level are counted as part of this one.Complexity
- Time — O(n): each node visited once.
- Space — O(n): the BFS queue.
Common Pitfalls
- Take the last node of each level. Taking the first gives the left side view --
1 2 5where the right side is1 3 4. - Snapshot the level size before the inner loop. Reading
len(q)inside it sees the children you just appended, so the level boundary dissolves and levels run together.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rightSideView(self, root):
if not root: return []
from collections import deque
res=[]; q=deque([root])
while q:
n=len(q)
for i in range(n):
node=q.popleft()
if i==n-1: res.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
return resimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int[] rightSideView(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null)return new int[]{};
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int sz=q.size();
for(int i=0;i<sz;i++) {
TreeNode n=q.poll();
if(i==sz-1)res.add(n.val);
if(n.left!=null)q.add(n.left);
if(n.right!=null)q.add(n.right);
}
}
int[] r=new int[res.size()];
for(int i=0;i<r.length;i++)r[i]=res.get(i);
return r;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(!root)return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int sz=q.size();
for(int i=0;i<sz;i++) {
TreeNode* n=q.front();
q.pop();
if(i==sz-1)res.push_back(n->val);
if(n->left)q.push(n->left);
if(n->right)q.push(n->right);
}
}
return res;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number[]}
*/ var rightSideView = function(root) {
if(!root)return [];
const res=[];
let q=[root];
while(q.length) {
const nq=[];
for(let i=0;i<q.length;i++) {
const node=q[i];
if(i===q.length-1)res.push(node.val);
if(node.left)nq.push(node.left);
if(node.right)nq.push(node.right);
}
q=nq;
}
return res;
};