↻one more pass.
Trees · Medium

Binary Tree Right Side View: the idea to remember.

Return the visible value at each depth when a binary tree is viewed from the right.

Solve on LeetCode ↗

The core insight

Visit the tree level by level, recording the final node processed at each depth.

Why it works

A left to right level order visits the rightmost existing node of that level last.

The mistake to avoid

The visible node may come from a left subtree when the right subtree is shorter.

Time: O(n)Space: O(w), maximum level width

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Visit the tree level by level, recording the final node processed at each depth.
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();
    if (root == null) return list;
    bfs(list, root);
    return list;
}

public void bfs(List<Integer> list, TreeNode root) {
    Queue<TreeNode> q = new LinkedList<>();
    q.offer(root);
    while (!q.isEmpty()) {
        int levelSize = q.size();
        for (int i = 0; i < levelSize; i++) {
            TreeNode cur = q.poll();
            if (i == 0) list.add(cur.val);
            if (cur.right != null) q.offer(cur.right);
            if (cur.left != null) q.offer(cur.left);
        }
    }
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.