educative.io

Right View of a Binary Tree solution

Why does the solution have this additional check:
if (i == levelSize - 1) result.add(currentNode);

Every time the for loop ends, the “current” TreeNode, I believe will have the rightmost value
So once the for loops ends, without any check, we can just do result.add(current);

As this is a breadth-first search, the outermost for loop is looping through the levels of the node. Hence, the variable ‘i’, bound by the condition i<levelSize, is finding the last node for each level of the tree. The inner condition result.add(current) is used to check if the node is indeed the last node of the level. Without this condition, the while loop will simply traverse through the tree without adding any value to the queue.