classSolution{ public List<Integer> rightSideView(TreeNode root){ Map<Integer, Integer> rightmostValueAtDepth = new HashMap<Integer, Integer>(); int max_depth = -1;
/* These two Queues are always synchronized, providing an implicit * association values with the same offset on each Queue. */ Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); Queue<Integer> depthQueue = new LinkedList<Integer>(); nodeQueue.add(root); depthQueue.add(0);
while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.remove(); int depth = depthQueue.remove();
if (node != null) { max_depth = Math.max(max_depth, depth);
/* The last node that we encounter at a particular depth contains * the correct value, so the correct value is never overwritten. */ rightmostValueAtDepth.put(depth, node.val);
/* Construct the solution based on the values that we end up with at the * end. */ List<Integer> rightView = new ArrayList<Integer>(); for (int depth = 0; depth <= max_depth; depth++) { rightView.add(rightmostValueAtDepth.get(depth)); }