Binary Tree Right Side View — LeetCode 199 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#199
Reading time
4 min

The problem

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        if root is None:
            return ans
        q = deque([root])
        while q:
            ans.append(q[0].val)
            for _ in range(len(q)):
                node = q.popleft()
                if node.right:
                    q.append(node.right)
                if node.left:
                    q.append(node.left)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 199. Binary Tree Right Side View is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, Grind 75, LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 199. Binary Tree Right Side View?
LeetCode 199. Binary Tree Right Side View is rated Medium on LeetCode.
What is the time complexity of LeetCode 199. Binary Tree Right Side View?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 199. Binary Tree Right Side View?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 199. Binary Tree Right Side View cover?
LeetCode 199. Binary Tree Right Side View is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview