Maintained by Vikas Dulgunde, software engineer
You are handed a binary tree, but instead of node objects you get a flat array laid out in level-order. Index 0 is the root, and for any node at index i its left child sits at index 2i+1 and its right child at index 2i+2. A null entry means there is no node in that slot.
Picture yourself standing to the right of the tree and looking across it. On each horizontal level you can only see one node: the last one that is actually present on that level. Your job is to collect those visible values from the top level down to the bottom.
The rightmost visible node on a level is not always a right child. If the right subtree is missing at some depth but the left subtree keeps going, the deepest left-side node becomes the one you see. So you cannot just walk right children; you have to look at the whole level and take the last real node on it.
Return the visible values as an array ordered from the top level to the deepest level. An empty input array means there is no tree, so the answer is an empty array.
Level 0 has only node 1. Level 1 has nodes 2 and 3, so 3 is rightmost. Level 2 has node 5 (right child of 2) and node 4 (right child of 3); 4 is the last real node, so it is visible.
The root 1 has no left child and right child 3. Each level holds a single node, so both are visible.
This is a left-leaning chain. Every level contains exactly one node (1, then 2, then 3, then 4), so each one is the rightmost on its level even though they are all left children.
Visible test cases
The answer has one value per level of the tree, so think about processing the tree one level at a time rather than node by node.
From an index i in a level-order array, the children live at 2i+1 and 2i+2. Use that to expand a level into the next level's indices, skipping nulls.
Within a single level, keep scanning left to right and remember the last present node you saw. That last node is the one visible from the right.
Walk the tree one level at a time. For each level, scan its nodes left to right and record the last non-null value, which is exactly what the right-side viewer sees.
Recurse depth first but always descend the right side before the left. The first time you reach a new depth, that node is the rightmost visible one for its level.