BFS, last of each level
Time O(n) Space O(width)Level-order traversal; when polling the last node of a level (size reaches 1), record it.
import java.util.*;
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
for (int size = q.size(); size > 0; size--) {
TreeNode n = q.poll();
if (size == 1) out.add(n.val);
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
}
return out;
}
}Verdict: Clear.