← Advanced Trees

Drill #93 — Binary tree right side view

Medium Queue by Level Advanced Trees

In plain English: Look at a binary tree from the right side and list the nodes you can see at each level.

Level-order traversal where you record the last node at each level — that is the rightmost node visible from the right side.

Prompt

Given a binary tree, return the values of the nodes you can see from the right side, ordered from top to bottom.

Try to write it from scratch before scrolling down.

Solution

from collections import deque

def right_side_view(root):
    if not root:
        return []
    result = []
    q = deque([root])
    while q:
        level_size = len(q)
        for i in range(level_size):
            node = q.popleft()
            if i == level_size - 1:
                result.append(node.val)  # last node in level = rightmost
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
    return result

# Test: tree [1,2,3,null,5,null,4] => [1, 3, 4]
O(n) time · O(n) space

Related Micro Drills

← Drill #92 Drill #94 →