Train of thought

Order traversal, add the last element of each layer to the result.

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(! queue.isEmpty()) {int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.removeFirst();
                if(cur.left ! =null) {
                    queue.add(cur.left);
                }
                if(cur.right ! =null) {
                    queue.add(cur.right);
                }
                / / simplified version
                if (i == size - 1) { res.add(cur.val); }}}returnres; }}Copy the code