privatestaticclassSolution{ public List<Integer> rightSideView(TreeNode root){ if (root == null) { returnnew ArrayList<>(); } List<Integer> res = new LinkedList<>(); ArrayDeque<TreeNode> deque = new ArrayDeque<>(); deque.push(root);
while (!deque.isEmpty()) { int size = deque.size(); int index = 0; for (int i = 0; i < size; i++) { TreeNode node = deque.poll(); if (i == size - 1) { res.add(node.val); } if (node.left != null) { deque.addLast(node.left); } if (node.right != null) { deque.addLast(node.right); } } } return res; } }