Given the root of a binary tree, imagine you are standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom.
while (!queue.isEmpty()) { intsize= queue.size(); for (inti=0; i < size; i++) { TreeNodenode= queue.poll(); if (i == size - 1) { // last node in this level result.add(node.val); } if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } } return result; } }
💡 Approach 2: DFS (Right-First Preorder)
We can also use DFS, always visiting right child first so the first node we encounter at each depth is the visible one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = newArrayList<>(); dfs(root, 0, result); return result; }