Q: Given a binary tree, imagine yourself standing on the right side of it, returning the node values that can be seen from the right side, in order from top to bottom.
A:
Hierarchical traversal, take the last one of each layer.
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
while (!q.isEmpty()) {
while (size != 0) {
if (size == 1) {
res.add(q.peek().val);
}
TreeNode curr = q.poll();
if (curr.left != null) {
q.add(curr.left);
}
if (curr.right != null) {
q.add(curr.right);
}
size--;
}
size = q.size();
}
return res;
}