15% off all plans & roadmaps Use code
See plansBinary Tree Right Side View
- LeetCode 199
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Level Order Traversal
Updated
TL;DR: Return the last node of every level of the tree. Walk the tree level by level with a queue, or go right first with DFS and keep the first node seen at each new depth.
Problem
Given the root of a binary tree, picture yourself standing on its right side, looking at the tree. Return the values of the nodes you can see, ordered from top to bottom.
Example 1
Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
Example 2
Input: root = [1,2,3,4,null,null,null,5] Output: [1,3,4,5]
Example 3
Input: root = [1,null,3] Output: [1,3]
Example 4
Input: root = [] Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Constraints that matter
- At most 100 nodes means even an O(n^2) scan finishes instantly, so a repeated-search brute force is legal here. The interview still expects O(n).
- Node values lie in [-100, 100], so 0 and negative values are valid. Never use a falsy check or a sentinel like 0 or -1 to mean not found.
- The tree can be empty (0 nodes), so the root itself can be null and the answer is an empty list.
- Height is at most 100, so recursive DFS cannot overflow the stack in any of the six languages.
Hints
Hint 1
The view from the right shows exactly one node per depth: the rightmost node at that depth.
Hint 2
You need one value per depth.
Solution
Intuition
The view from the right shows exactly one node per depth: the rightmost node at that depth. That is the whole problem. Once you phrase it as one answer per level, the pattern is level order traversal.
It is like a row of mailboxes, one per floor, where the floor number is the depth. The result list is that row of mailboxes, and a right-first walk through the building drops a note in a mailbox only when it is empty, so the first person to reach each floor from the right leaves the note and everyone later on that floor is ignored.
A common first guess is to follow right pointers from the root. That fails when the left subtree is deeper. In the tree [1,2,3,4,null,null,null,5], node 3 has no children, so the nodes 4 and 5 on the left side show up below it. The right edge of the picture is not the right spine of the tree.
There are two clean ways to get one node per level. With BFS, you process each level left to right and keep the last node. With DFS, you visit the right child before the left child and record a node only when its depth is new. The first node to reach a depth in right-first order is the rightmost one at that depth.
Both work for the same reason. Depth decides which slot in the answer a node can fill, and position within the level decides who wins that slot. Pick the winner rule (last in BFS, first in right-first DFS) and each level yields exactly one value.
Worked example
Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Explanation: Level 0 holds only 1. Level 1 holds 2 and 3, and 3 is on the right. Level 2 holds 5 and 4, and 4 is on the right. So you see 1, 3, 4 from top to bottom.
Approach 1: Brute force: search the whole tree once per depth
You need one value per depth. The most direct way is to ask, for each depth d starting at 0, "what is the rightmost node at depth d?" and answer each question with a fresh search from the root.
To answer one question, walk down from the root and count depth. At depth d, return the node. At every step try the right child first, then the left.
The first hit is the rightmost node at that depth. If the search returns nothing, the tree has no nodes that deep, so stop.
Steps
- Start with an empty result list and depth d = 0.
- Call
find(root, d), which returns the rightmost value at depth d, or nothing if no node is that deep. - In
find, return null when the node is null, and return the node's value when d is 0. - Otherwise call
findon the right child with d - 1. If it finds something, return it. - If the right side found nothing, return
findon the left child with d - 1. - If
findreturns nothing for the root, stop. Otherwise append the value, increment d and repeat.
Dry run
Tree [1,2,3,null,5,null,4], so 1 has children 2 and 3, node 2 has right child 5, and node 3 has right child 4.
- d = 0:
find(1, 0)returns 1. Result[1]. - d = 1:
find(1, 1)goes right to node 3 with d = 0 and returns 3. Result[1,3]. - d = 2:
find(1, 2)goes right to 3 with d = 1, then right to 4 with d = 0 and returns 4. Result[1,3,4]. - d = 3:
find(1, 3)tries 3 then 4 and finds nothing, since 4 has no children. It then tries 2 then 5 and finds nothing. It returns nothing, so the loop stops.
The answer is [1,3,4].
Complexity
| Time | O(n * h) |
|---|---|
| Space | O(h) |
Let n be the node count and h the height. Each call to find visits at most every node once, so one depth costs O(n). The loop runs h + 1 times, h successes and one final failure, so the total is O(n * h).
In a skewed tree h is close to n, which makes this O(n^2) in the worst case. Space is the recursion depth, at most h, plus the output list.
PythonTested in our runner
from typing import List, Optional
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
d = 0
while True:
v = self.find(root, d)
if v is None:
break
res.append(v)
d += 1
return res
def find(self, node, d):
# rightmost value at depth d below node, or None
if node is None:
return None
if d == 0:
return node.val
r = self.find(node.right, d - 1)
if r is not None:
return r
return self.find(node.left, d - 1)
JavaTested in our runner
import java.util.*;
class Solution {
public int[] rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
int d = 0;
while (true) {
Integer v = find(root, d);
if (v == null) break;
res.add(v);
d++;
}
int[] out = new int[res.size()];
for (int i = 0; i < out.length; i++) out[i] = res.get(i);
return out;
}
private Integer find(TreeNode node, int d) {
if (node == null) return null;
if (d == 0) return node.val;
Integer r = find(node.right, d - 1);
if (r != null) return r;
return find(node.left, d - 1);
}
}
C++Tested in our runner
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
int d = 0;
int val;
while (find(root, d, val)) {
res.push_back(val);
d++;
}
return res;
}
private:
bool find(TreeNode* node, int d, int& out) {
if (!node) return false;
if (d == 0) {
out = node->val;
return true;
}
if (find(node->right, d - 1, out)) return true;
return find(node->left, d - 1, out);
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
const find = (node, d) => {
if (node === null || node === undefined) return null;
if (d === 0) return node.val;
const r = find(node.right, d - 1);
if (r !== null) return r;
return find(node.left, d - 1);
};
const res = [];
let d = 0;
while (true) {
const v = find(root, d);
if (v === null) break;
res.push(v);
d++;
}
return res;
};
GoTested in our runner
func rightSideView(root *TreeNode) []int {
res := []int{}
for d := 0; ; d++ {
v, ok := findAtDepth(root, d)
if !ok {
break
}
res = append(res, v)
}
return res
}
func findAtDepth(node *TreeNode, d int) (int, bool) {
if node == nil {
return 0, false
}
if d == 0 {
return node.Val, true
}
if v, ok := findAtDepth(node.Right, d-1); ok {
return v, true
}
return findAtDepth(node.Left, d-1)
}
C#Tested in our runner
public class Solution {
public int[] rightSideView(TreeNode root) {
var res = new List<int>();
int d = 0;
while (true) {
int? v = Find(root, d);
if (v == null) break;
res.Add(v.Value);
d++;
}
return res.ToArray();
}
private int? Find(TreeNode node, int d) {
if (node == null) return null;
if (d == 0) return node.val;
int? r = Find(node.right, d - 1);
if (r != null) return r;
return Find(node.left, d - 1);
}
}

Solution pattern
Level Order Traversal
Approach 2: BFS level order, keep the last nodeLevel Order Traversal
What's slow: the brute force restarts from the root for every depth, so it re-walks the upper levels again and again. Finding depth 5 re-visits all nodes on depths 0 to 4 on the way down.
The insight that fixes it: a queue already hands you the tree one level at a time, left to right. Take a snapshot of the queue size at the start of each round. That count is exactly the number of nodes on the current level.
The last node you pop in that round is the rightmost one, so record it. Each node is touched once.
Steps
- Return an empty list if
rootis null. - Put
rootin a queue and create an empty result list. - While the queue is not empty, read its size into
size. That is the current level. - Pop
sizenodes in a loop. Push each node's left child, then its right child, when they exist. - When the loop index is
size - 1, append that node's value to the result. - Return the result when the queue is empty.
Dry run
Tree [1,2,3,null,5,null,4].
- Level 0: the queue is
[1], size 1. Pop 1, push 2 and 3. It is the last in its level, so record 1. - Level 1: the queue is
[2,3], size 2. Pop 2 (index 0), push 5. Pop 3 (index 1), push 4. Index 1 is the last, so record 3. - Level 2: the queue is
[5,4], size 2. Pop 5 (index 0), no children. Pop 4 (index 1), no children. Record 4. - The queue is empty. The result is
[1,3,4].
Complexity
| Time | O(n) |
|---|---|
| Space | O(w) |
Let n be the node count and w the maximum width of any level. Every node is pushed once and popped once, each in O(1), so time is O(n). The queue holds at most two adjacent levels at once, which is O(w). For a complete tree w is about n / 2, so the worst case is O(n).
PythonTested in our runner
from collections import deque
from typing import List, Optional
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
if root is None:
return res
queue = deque([root])
while queue:
size = len(queue) # snapshot: nodes on this level
for i in range(size):
node = queue.popleft()
if i == size - 1:
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
JavaTested in our runner
import java.util.*;
class Solution {
public int[] rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return new int[0];
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // nodes on this level
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == size - 1) res.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
int[] out = new int[res.size()];
for (int i = 0; i < out.length; i++) out[i] = res.get(i);
return out;
}
}
C++Tested in our runner
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 size = q.size(); // nodes on this level
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
if (i == size - 1) res.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
const res = [];
if (!root) return res;
let level = [root];
while (level.length > 0) {
// the last node of the level is the visible one
res.push(level[level.length - 1].val);
const next = [];
for (const node of level) {
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
level = next;
}
return res;
};
GoTested in our runner
func rightSideView(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
level := []*TreeNode{root}
for len(level) > 0 {
res = append(res, level[len(level)-1].Val)
next := []*TreeNode{}
for _, node := range level {
if node.Left != nil {
next = append(next, node.Left)
}
if node.Right != nil {
next = append(next, node.Right)
}
}
level = next
}
return res
}
C#Tested in our runner
public class Solution {
public int[] rightSideView(TreeNode root) {
var res = new List<int>();
if (root == null) return res.ToArray();
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
int size = queue.Count; // nodes on this level
for (int i = 0; i < size; i++) {
TreeNode node = queue.Dequeue();
if (i == size - 1) res.Add(node.val);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
}
return res.ToArray();
}
}
Approach 3: Right-first DFS with depthOptimal
What's slow: BFS is already O(n) in time, but its queue can hold a whole level, which is up to about n / 2 nodes. The answer only needs one node per level, so you are storing far more than you use.
The insight that fixes it: visit the right child before the left child and carry the depth down the recursion. The first node you reach at a new depth is the rightmost node at that depth, because everything to its right in that level was visited first and did not exist.
The result list length doubles as a record of the deepest level seen so far. If the depth equals the current list length, this node is the first at its depth, so append it. Memory is now the recursion stack, which is the tree height.
Steps
- Create an empty result list.
- Define
dfs(node, depth). Return immediately ifnodeis null. - If
depthequals the length of the result list, appendnode.val. No node at this depth has been seen yet. - Call
dfs(node.right, depth + 1)first. - Then call
dfs(node.left, depth + 1). - Call
dfs(root, 0)and return the result.
Dry run
Tree [1,2,3,null,5,null,4]. Right child always goes first.
| Step | Visit (depth) | Result length | Action | Result |
|---|---|---|---|---|
| 1 | 1 (0) | 0 | depth 0 equals 0, append | [1] |
| 2 | 3 (1) | 1 | depth 1 equals 1, append | [1,3] |
| 3 | 4 (2) | 2 | depth 2 equals 2, append | [1,3,4] |
| 4 | 4's children (3) | 3 | both null, return | [1,3,4] |
| 5 | 3's left (2) | 3 | null, return | [1,3,4] |
| 6 | 2 (1) | 3 | depth 1 is not 3, skip | [1,3,4] |
| 7 | 5 (2) | 3 | depth 2 is not 3, skip | [1,3,4] |
| 8 | 5's children, 2's left | 3 | all null, return | [1,3,4] |
Nodes 2 and 5 are on the left, and levels 1 and 2 were already filled by 3 and 4. The answer is [1,3,4].
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) |
Let n be the node count and h the tree height. The recursion visits each node exactly once and does O(1) work per visit, so time is O(n). The call stack never exceeds h + 1 frames, and the result list has one entry per level, at most h + 1. So extra space is O(h), which is O(log n) for a balanced tree and O(n) for a skewed one.
PythonTested in our runner
from typing import List, Optional
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
def dfs(node, depth):
if node is None:
return
# first node reached at this depth is the rightmost
if depth == len(res):
res.append(node.val)
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)
dfs(root, 0)
return res
JavaTested in our runner
import java.util.*;
class Solution {
public int[] rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, 0, res);
int[] out = new int[res.size()];
for (int i = 0; i < out.length; i++) out[i] = res.get(i);
return out;
}
private void dfs(TreeNode node, int depth, List<Integer> res) {
if (node == null) return;
// first node reached at this depth is the rightmost
if (depth == res.size()) res.add(node.val);
dfs(node.right, depth + 1, res);
dfs(node.left, depth + 1, res);
}
}
C++Tested in our runner
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
dfs(root, 0, res);
return res;
}
private:
void dfs(TreeNode* node, int depth, vector<int>& res) {
if (!node) return;
// first node reached at this depth is the rightmost
if (depth == (int)res.size()) res.push_back(node->val);
dfs(node->right, depth + 1, res);
dfs(node->left, depth + 1, res);
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
const res = [];
const dfs = (node, depth) => {
if (!node) return;
// first node reached at this depth is the rightmost
if (depth === res.length) res.push(node.val);
dfs(node.right, depth + 1);
dfs(node.left, depth + 1);
};
dfs(root, 0);
return res;
};
GoTested in our runner
func rightSideView(root *TreeNode) []int {
res := []int{}
var dfs func(node *TreeNode, depth int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
// first node reached at this depth is the rightmost
if depth == len(res) {
res = append(res, node.Val)
}
dfs(node.Right, depth+1)
dfs(node.Left, depth+1)
}
dfs(root, 0)
return res
}
C#Tested in our runner
public class Solution {
public int[] rightSideView(TreeNode root) {
var res = new List<int>();
Dfs(root, 0, res);
return res.ToArray();
}
private void Dfs(TreeNode node, int depth, List<int> res) {
if (node == null) return;
// first node reached at this depth is the rightmost
if (depth == res.Count) res.Add(node.val);
Dfs(node.right, depth + 1, res);
Dfs(node.left, depth + 1, res);
}
}
Common mistakes
- Following only
node = node.rightfrom the root. This misses left-subtree nodes that sit below the right spine. Handle every level, not only the right edge. - Writing
for i in range(len(queue))in a way that re-reads the size each time, such aswhile i < queue.size()in Java or C++. The queue grows as you push children and the level boundary shifts. Snapshotsizebefore the inner loop starts. - Pushing the right child before the left child in BFS and still taking the last node of the level. The last node is then the leftmost. Push left first, or take the first node instead.
- Writing
if (!node) ...style checks on values, or using 0 as a not-found sentinel in the brute force. Values can be 0 and negative. Compare against null, not against falsy or a number. - Visiting left first in the DFS and recording on
depth == len(res). That produces the left side view. Recurse intonode.rightbeforenode.left. - Forgetting the empty tree. In BFS,
queue.push(root)with a null root crashes on the first pop. Return an empty result whenrootis null.
Edge cases
- Empty tree
[]: return an empty list. - Single node
[5]: return[5]. - Only left children,
[1,2,null,3]: the answer is[1,2,3], since each left child is visible. - Left subtree deeper than the right,
[1,2,3,4,null,null,null,5]: the answer is[1,3,4,5]. - Node values of 0 or negative numbers: the value 0 must still be recorded, and no sentinel may collide with it.
- Maximum size, 100 nodes in a single chain: recursion depth is 100, which is safe in every language.
Follow-ups interviewers ask
- How would you return the left side view instead?
- Flip the rule. In BFS, record the first node of each level (index 0). In DFS, visit the left child before the right child and keep the same depth equals length check. Nothing else changes.
- Can you avoid the queue and use only O(h) extra space?
- Yes, use the right-first DFS. It stores only the recursion stack, at most h + 1 frames, plus the output. For a balanced tree that is O(log n), against up to n / 2 for a BFS queue. For a skewed tree both are O(n).
- What if the tree is too deep for recursion?
- Run the DFS with an explicit stack of (node, depth) pairs. Push the left child first so the right child is popped first. Keep the same rule: append when depth equals the result length. Time stays O(n), and the stack depth is bounded by the height plus the siblings waiting.
Binary Tree Right Side View FAQ
What is the time complexity of Binary Tree Right Side View?
The BFS and right-first DFS solutions both run in O(n), where n is the number of nodes, because every node is visited once with constant work. The brute force that re-searches for each depth costs O(n * h), which is O(n^2) on a skewed tree.
Why use level order traversal for Binary Tree Right Side View?
The answer holds exactly one node per depth, and BFS hands you the tree one depth at a time in left-to-right order. The last node of each level is the rightmost one, so you need no extra bookkeeping beyond a size snapshot.
Can Binary Tree Right Side View be solved in O(1) extra space?
Not with ordinary traversal. Both BFS and DFS need a queue or a stack, and the output itself has up to h entries. A Morris-style threaded traversal can avoid the stack, but it modifies the tree temporarily and is not what interviewers expect here.
Why use DFS for Binary Tree Right Side View instead of BFS?
Right-first DFS uses O(h) stack space instead of a queue as wide as the widest level. It records a node only when its depth is new, so the first node seen per depth is the rightmost. Both are O(n) in time.
How does the solution handle a left subtree that is deeper than the right?
Levels that the right side does not reach have only left nodes. In BFS, the last node of such a level is a left-side node, and in DFS, the first node reaching that depth comes from the left subtree. Both therefore show those nodes.
Why does the Java or C# solution build a list first?
The starter code returns an int array, but the number of levels is unknown in advance. Collect values in a list, then copy them into an array of the final size at the end.
Asked at
See which companies ask this — Pro
Related problems
- Binary Tree Level Order Traversal · same technique: Level Order Traversal
- Binary Tree Zigzag Level Order Traversal · same technique: Level Order Traversal
- Find Largest Value in Each Tree Row · same technique: Level Order Traversal
- Maximum Level Sum of a Binary Tree · same technique: Level Order Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Kth Smallest Element in a BST · same pattern: Tree Traversal Patterns (DFS & BFS)
- Count Good Nodes in Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)