if (i ==0) {res.add(cur.val);}// right first, so i == 0 is the right side's first nodeif (cur.right!=null) queue.offer(cur.right); if (cur.left!=null) queue.offer(cur.left);
or
if (i == size -1) {res.add(cur.val);}// or left, right, so size - 1 is the right side's first nodeif (cur.left!=null) queue.offer(cur.left);if (cur.right!=null) queue.offer(cur.right);
time: O(n)
space: O(D) to keep the queues, where D is a tree diameter. Let's use the last level to estimate the queue size. This level could contain up to N/2N/2 tree nodes in the case of complete binary tree.
classSolution {publicList<Integer> rightSideView(TreeNode root) {List<Integer> res =newArrayList<>();if (root ==null) return res;Queue<TreeNode> queue =newLinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size =queue.size();for (int i =0; i < size; i++) {TreeNode cur =queue.poll();if (i ==0) {res.add(cur.val); }if (cur.right!=null) queue.offer(cur.right);if (cur.left!=null) queue.offer(cur.left); } }return res; }}