Browse curriculum

Binary Tree Right Side View (LeetCode 199)

Binary Tree Right Side View (LeetCode 199): list the node visible on each level when the tree is viewed from the right, top level first.

Medium
10 min
Solve on LeetCode

Examples

Input:root = [1,2,3,null,5,null,4]
Output:[1,3,4]
Explain:

The last node of each level.

Input:root = [1,2,3,4,null,null,null,5]
Output:[1,3,4,5]
Explain:

5 is a left child, but nothing on the right reaches its depth.

Input:root = [1,null,3]
Output:[1,3]
Explain:

One node per level.

Input:root = []
Output:[]
Explain:

Nothing to see.

Problem Understanding

Picture the binary tree under root from its right side. List the value of the node visible on each level, from the top level down.

  • Essentially: For every level, pick the last node.

Algorithm Strategy

We can use BFS (Level Order Traversal).

  1. Process the tree level by level.
  2. Each level is dequeued left to right, so the node dequeued at position size - 1 (the last of its level) is the rightmost node.
  3. Add that node's value to our result list.

Interactive Visualization

iN = POSITION IN THE LEVEL · GREEN = SEEN FROM THE RIGHT

ENQUEUE ROOT

i

:

size

:

queue (front first)

1

result

[]

 

Put the root, 1, in the queue

Next

A new level: size = 1. The node dequeued at position 0 is the one seen from the right

Free preview: the first 6 of 17 steps

Tree

Each node on the level being processed carries its position, i0, i1, …. The node dequeued at position size − 1 is the one visible from the right, and it stays green. Try Example 2: the rightmost node on the deepest level is a left child.

Dry Run

Tree: [1, 2, 3, null, 5, null, 4]: root 1; 2 has a right child 5; 3 has a right child 4.

Level Nodes Rightmost Result
0 [1] 1 [1]
1 [2, 3] 3 [1, 3]
2 [5, 4] 4 [1, 3, 4]

Edge Cases & Common Mistakes

Edge Cases:

  • Null Root: Return [].
  • Left-skewed Tree: You still see the left nodes if there are no right nodes blocking them (Right Side View != Right Children only!).

Common Mistakes:

  • Only traversing node.right. (Wrong! You might see left children if the right side is shorter).

Solution Code

BFS approach.

Binary Tree Right Side View Code
1var rightSideView = function(root) {
2 const result = [];
3 if (!root) {
4 return result;
5 }
6 const queue = [root];
7 let head = 0;
8 while (head < queue.length) {
9 const size = queue.length - head;
10 for (let i = 0; i < size; i++) {
11 const node = queue[head++];
12 if (i === size - 1) {
13 result.push(node.val);
14 }
15 if (node.left) {
16 queue.push(node.left);
17 }
18 if (node.right) {
19 queue.push(node.right);
20 }
21 }
22 }
23 return result;
24};

Binary Tree Right Side View in Python, Java, C++, TypeScript and C

Binary Tree Right Side View in Python
from collections import deque


class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        result = []
        if not root:
            return result
        queue = deque([root])
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.popleft()
                if i == size - 1:
                    result.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return result
Binary Tree Right Side View in Java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                    result.add(node.val);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return result;
    }
}
Binary Tree Right Side View in C++
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result;
        if (!root) {
            return result;
        }
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = q.front();
                q.pop();
                if (i == size - 1) {
                    result.push_back(node->val);
                }
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
        }
        return result;
    }
};
Binary Tree Right Side View in TypeScript
function rightSideView(root: TreeNode | null): number[] {
    const result: number[] = [];
    if (!root) {
        return result;
    }
    const queue: TreeNode[] = [root];
    let head = 0;
    while (head < queue.length) {
        const size = queue.length - head;
        for (let i = 0; i < size; i++) {
            const node = queue[head++];
            if (i === size - 1) {
                result.push(node.val);
            }
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
    }
    return result;
}
Binary Tree Right Side View in C
int* rightSideView(struct TreeNode* root, int* returnSize) {
    int* result = malloc(100 * sizeof(int));
    *returnSize = 0;
    if (!root) {
        return result;
    }
    struct TreeNode** queue = malloc(100 * sizeof(struct TreeNode*));
    int head = 0, tail = 0;
    queue[tail++] = root;
    while (head < tail) {
        int size = tail - head;
        for (int i = 0; i < size; i++) {
            struct TreeNode* node = queue[head++];
            if (i == size - 1) {
                result[(*returnSize)++] = node->val;
            }
            if (node->left) {
                queue[tail++] = node->left;
            }
            if (node->right) {
                queue[tail++] = node->right;
            }
        }
    }
    free(queue);
    return result;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Seed the queue

    Return an empty list for an empty tree; otherwise enqueue the root.

  2. Walk one level

    Read the queue's size and dequeue that many nodes, enqueueing their children.

  3. Record the last

    When the position i equals size − 1, append that node's value to the result.

Frequently asked questions

Can the right side view include a left child?

Yes. If nothing on the right side of the tree reaches a certain depth, the rightmost node at that depth may be a left child. That is why following only right pointers gives the wrong answer.


Why is the last node of a level the visible one?

BFS dequeues each level from left to right, so the node at position size − 1 is the rightmost node on that level: the one nothing else hides from the right.


Can this be solved with DFS?

Yes: visit the right child before the left and record the first node reached at each new depth. Both run in O(n) time.

New to the technique behind this problem? Watch it run step by step:

Breadth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description