/* These two stacks are always synchronized, providing an implicit * association values with the same offset on each stack. */ Stack<TreeNode> nodeStack = newStack<TreeNode>(); Stack<Integer> depthStack = newStack<Integer>(); nodeStack.push(root); depthStack.push(0);
while (!nodeStack.isEmpty()) { TreeNodenode= nodeStack.pop(); intdepth= depthStack.pop();
if (node != null) { max_depth = Math.max(max_depth, depth);
/* The first node that we encounter at a particular depth contains * the correct value. */ if (!rightmostValueAtDepth.containsKey(depth)) { rightmostValueAtDepth.put(depth, node.val); }
/* Construct the solution based on the values that we end up with at the * end. */ List<Integer> rightView = newArrayList<Integer>(); for (intdepth=0; depth <= max_depth; depth++) { rightView.add(rightmostValueAtDepth.get(depth)); }