Start learning free

LESSON 441 OF 569 · BINARY TREES

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

Practice O(n) Read the full explanation

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

From the right you see exactly one node on each level: the rightmost node of that level, the last one when you read the level from left to right. It can belong to the left subtree, when the right subtree doesn't reach that deep. An empty tree shows nothing.

The trees below are written in level order (top to bottom, left to right), with None for a missing child.

 

Example 1:

    1
   / \
  2   3
   \   \
    5   4

Input: root = [1,2,3,None,5,None,4]
Output: [1,3,4]
Explanation: The first level is just 1. On the second level, 3 hides 2. On the third level, 4 hides 5.

Example 2:

      1
     / \
    2   3
   /
  4

Input: root = [1,2,3,4]
Output: [1,3,4]
Explanation: The third level has only 4. It is in the left subtree, but nothing stands to its right, so you see it.

Example 3:

Input: root = []
Output: []
Explanation: An empty tree has no levels, so you see no nodes.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
  • Values may repeat.

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 Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free