LeetCode 199: Binary Tree Right Side View — Python Solution

LeetCode 199: Binary Tree Right Side View is a Medium binary tree bfs problem. This Python walkthrough develops a level-order last node solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree BFS
Reusable patternlevel-order last node
ComplexityO(n) time and O(w) space

Recognizing the pattern

Breadth-first search is the natural fit when the answer is grouped by depth or depends on the first visit at a level.

For this problem specifically, process the tree level by level and record the value of the final node dequeued from each level. The invariant worth writing beside the code is: The queue segment for a level is ordered left-to-right, so its final node is visible from the right.

Step-by-step algorithm

  1. Identify the input state consumed by rightSideView(root) and initialize the data required by the level-order last node pattern.
  2. Process the tree level by level and record the value of the final node dequeued from each level.
  3. After each update, verify the page’s central invariant: The queue segment for a level is ordered left-to-right, so its final node is visible from the right.
  4. Finish only after the boundary behavior is covered: An empty tree produces an empty list.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

from collections import deque

class Solution:
    def rightSideView(self, root):
        if not root:
            return []
        queue, answer = deque([root]), []
        while queue:
            for _ in range(len(queue)):
                node = queue.popleft()
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
            answer.append(node.val)
        return answer

Reading the implementation

The main entry point is rightSideView(root). The named working state includes queue, node; those variables make the level-order last node state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, process the tree level by level and record the value of the final node dequeued from each level.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Process the tree level by level and record the value of the final node dequeued from each level. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the queue segment for a level is ordered left-to-right, so its final node is visible from the right.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(w) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Depth-first search can carry an explicit depth and build the same result, but level boundaries are less direct. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

root=tree([3,9,20,None,None,15,7]); assert Solution().rightSideView(root)==[3,20,7]

Common mistakes and edge cases

  • Problem-specific boundary: An empty tree produces an empty list.
  • Pattern-level pitfall: Capture the current queue length before processing a level so children do not leak into the same batch.
  • Invariant check: after every update, confirm that the queue segment for a level is ordered left-to-right, so its final node is visible from the right.

Interview review checklist

  • Explain why level-order last node matches the structure of this input.
  • State the invariant in one sentence before tracing code: The queue segment for a level is ordered left-to-right, so its final node is visible from the right.
  • Derive O(n) time and O(w) space from how many times each element or state is visited.
  • Test the boundary explicitly: An empty tree produces an empty list.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 236. Lowest Common Ancestor of a Binary Tree · Next: 637. Average of Levels in Binary Tree