Start learning free

LESSON 215 OF 314 · BINARY TREES

Binary Tree Right Side View in Python: Level Order with a Queue

Practice O(n) Read the full explanation

You get the root of a binary tree. Imagine you stand to its right and look at it. Return the values you can see, from the top row down.

On each row, you see only the node farthest to the right. It hides the others. If the right side is shorter, lower rows show nodes from the left side. For an empty tree, return an empty list.

In the examples, each tree is written row by row from the top. Each row goes left to right. None marks a missing child.

 

Example 1:

      6
     / \
    3   8
   /   /
  2   7

Input: root = [6,3,8,2,None,7]
Output: [6,8,7]
Explanation: The last node of each row is 6, then 8, then 7.
The 3 and the 2 hide behind them.

Example 2:

      5
     / \
    9   2
     \
      4
     /
    7

Input: root = [5,9,2,None,4,None,None,7]
Output: [5,2,4,7]
Explanation: The right side ends at 2.
Further down, 4 and 7 are alone on their rows.
So you see them, even though they sit under 9.

 

Constraints:

  • The tree has 0 to 100 nodes.
  • Each value is a whole number from -100 to 100.
  • A value can appear more than once.

Note:

The tutorial walks the tree level by level with a queue. The queue starts with the root. At the start of each round it holds exactly one level: count its nodes, take them out one by one from the front, and put each node's children (left, then right) at the back, where they wait for the next round. The last node taken out in a round is the rightmost node of its level: that is the one you see.

Each node enters and leaves the queue once, so the time is O(n) for a tree of n nodes. The queue holds at most about two levels at a time, which is O(n) extra space in the worst case.

STEP 1 OF 11
    Ctrl + Enter to check

    PYTHON · BINARY TREES

    Binary Tree Right Side View in Python, explained

    Problem overview

    The function rightSideView receives the root of a binary tree and returns the values you would see standing on its right side, from the top level down. The lesson provides the TreeNode class: each node has a val and two children, left and right, which are None when missing.

    From the right, exactly one node of each level is visible: the rightmost one. For the tree [1, 2, 3, None, 5, None, 4], the first level is just 1. On the second level 3 hides 2, and on the third level 4 hides 5, so the answer is [1, 3, 4]. An empty tree has no levels, so the answer is [].

    The visible node of a level is not always a right child. For [1, 2, 3, 4] the third level holds only 4, which is the left child of 2, and nothing stands to its right. The answer is still [1, 3, 4].

    Approach: visit the tree one level at a time

    A tempting shortcut is to follow right pointers from the root. On [1, 2, 3, 4] that gives [1, 3] and misses the 4, because the right branch ends one level too early. The answer depends on whole levels, so the solution should walk the tree level by level.

    That is a breadth-first search with a queue. The queue starts with the root. At the start of each round it holds exactly one level of the tree. The round counts those nodes, takes them out from the front one at a time, and puts their children at the back. Those children wait for the next round, and since the left child goes in before the right one, each level stays in left-to-right order. The last node taken out in a round is the rightmost node of its level, so its value goes into the answer.

    Running the loop on the first example and printing the queue at the start of each round gives:

    level [1] -> 1
    level [2, 3] -> 3
    level [5, 4] -> 4

    Each line shows the values in the queue and the one that is recorded. The third round shows why the order matters: 5 is the right child of 2 and 4 is the right child of 3, and 4 comes last because 2 was processed before 3.

    A depth-first search can solve this too, but the queue keeps the idea close to the question: one round per level, one value per round.

    Step by step

    1. Create result, an empty list that will receive one value per level.
    2. Handle the empty tree. If root is None, return the empty result right away, because the queue below needs a first node.
    3. Create the queue with deque([root]). A deque removes its first element quickly with popleft(), while list.pop(0) has to shift every other element.
    4. Loop while the queue is not empty. Each pass of this while loop handles one whole level.
    5. Store len(queue) in levelSize. At this moment the queue holds this level and nothing else, so the number is the level's width.
    6. Loop i over range(levelSize). The children added during this loop belong to the next level, and counting up to levelSize stops the loop before it reaches them.
    7. Take the next node from the front with queue.popleft().
    8. Record the last node of the level. When i == levelSize - 1, append node.val to result.
    9. Queue the left child if it exists.
    10. Queue the right child if it exists, right after the left one.
    11. Return result after the loops.

    The solution in Python

    class Solution:
        def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
            result = []
            if not root:
                return result
            queue = deque([root])
            while queue:
                levelSize = len(queue)
                for i in range(levelSize):
                    node = queue.popleft()
                    if i == levelSize - 1:
                        result.append(node.val)
                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)
            return result
    

    The Python details worth a closer look:

    • Truthiness. not root is true when root is None, and if node.left: is true when the child exists. A TreeNode object is truthy by default, even when its val is 0, so these tests look at the node, not at its value.
    • A deque in a while condition. An empty deque counts as false, so while queue: runs until there is nothing left to visit.
    • The length is read once. levelSize = len(queue) is taken before the inner loop starts and then stays fixed, while the queue itself keeps growing as children are added. i is the position within the level, which is what identifies its last node.

    Complexity

    Time: O(n). Every node enters the queue once and leaves it once, and each visit does a constant amount of work.

    Space: O(n). The queue holds at most two neighbouring levels at a time, and the widest level of a tree can hold a large share of its nodes, for example about half of them in a perfect tree. The answer itself has one value per level, which is at most n.

    Edge cases and common mistakes

    • An empty tree. [] returns []. Without the early return, deque([None]) would send None into the loop and fail on node.left.
    • A single node. [7] returns [7]: one level, one node, and it is the last of its level.
    • Following only right children. It gives [1, 3] for [1, 2, 3, 4], missing the left-subtree node on the third level.
    • A tree that leans left. [1, 2, None, 3, None, 4] returns [1, 2, 3, 4]: every level has one node, so every node is visible.
    • Equal values. [5, 5, 5, 5, 5] returns [5, 5, 5]. The answer holds one value per level, even when values repeat.
    • Re-reading the length. Comparing against len(queue) after children have been added counts nodes of the next level too, so the loop mixes two levels and the "last node" test points at the wrong node.
    • Pushing the right child first. The level then runs right to left, and the last node of a round becomes the leftmost one.

    Testing

    • [1, 2, 3, None, 5, None, 4] gives [1, 3, 4].
    • [1, 2, 3, 4] gives [1, 3, 4].
    • [] gives [].
    • [7] gives [7].
    • [1, None, 2, None, 3] gives [1, 2, 3].
    • [1, 2, 3, 4, 5, 6, 7] gives [1, 3, 7].
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free