Binary Tree Right Side View


Binary Tree Right Side View – LeetCode


Problem: Binary Tree Right Side View

Problem Statement

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.


Examples

Example 1

Input:
       1
     /   \
    2     3
     \     \
      5     4

Output: [1, 3, 4]

Example 2

Input: root = []
Output: []


Constraints


Intuition

The goal is to collect the last (rightmost) node from each level of the tree.
There are two common approaches:

  1. BFS (Level Order Traversal) – process nodes level by level.

  2. DFS (Right-First Recursive Traversal) – visit right children before left and take the first node encountered at each level.


Approach 1: BFS (Level Order Traversal)

Algorithm

Code (Java)

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = q.poll();
                if (i == size - 1) {
                    result.add(curr.val);
                }
                if (curr.left != null) q.offer(curr.left);
                if (curr.right != null) q.offer(curr.right);
            }
        }

        return result;
    }
}

Approach 2: DFS (Right-First Recursive Traversal)

Algorithm

Code (Java)

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, 0, result);
        return result;
    }

    private void dfs(TreeNode node, int level, List<Integer> result) {
        if (node == null) return;

        if (level == result.size()) {
            result.add(node.val);
        }

        dfs(node.right, level + 1, result);
        dfs(node.left, level + 1, result);
    }
}

Time and Space Complexity

For both approaches:


Dry Run (for DFS)

Input:

       1
     /   \
    2     3
     \     \
      5     4

Traversal order (DFS, right-first):
1 → 3 → 4 → 2 → 5


Conclusion

Choose based on context: