Python coding

Rightmost value on each level

Write rightmost_per_level(root): given the root of a binary tree, return the value of the last node of every level, reading each level from left to right, from the root's level down. It is what you would see looking at the tree from its right side. An empty tree gives []. Each TreeNode has val, left and right.

The tests call the provided run_rightmost_per_level(values), where values lists the tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3.

  • run_rightmost_per_level([5,3,8,1,null,null,9]) → [5,8,9]
  • run_rightmost_per_level([1,2,3,4]) → [1,3,4]
  • run_rightmost_per_level([]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Process the tree level by level (BFS): build the list of nodes of the next level from the nodes of the current one.

Hint 2

If children are added left before right, the last node in each level's list is the one visible from the right.

Hint 3

Following only right pointers is wrong: when the right subtree is shorter, the deeper levels show nodes from the left subtree, as in [1, 2, 3, 4].

Solution and why it works
pythonO(n) · O(w), w = widest level
# --- your code ---
def rightmost_per_level(root: "TreeNode | None") -> list[int]:
    view = []
    level = [root] if root else []
    while level:
        view.append(level[-1].val)       # levels are built left to right
        level = [child for node in level for child in (node.left, node.right) if child]
    return view


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def run_rightmost_per_level(values: list[int | None]) -> list[int]:
    return rightmost_per_level(build_tree(values))

Breadth-first search visits one level at a time; with children appended left before right, the last node of each level is the rightmost. Each node enters one level list once: O(n) time, memory up to the widest level. The trap is following right pointers only: in [1, 2, 3, 4] node 3 has no children, yet the third level still shows 4 from the left subtree. A DFS that goes right before left and keeps the first node seen at each depth also works.