15% off all plans & roadmaps Use code

See plans

Binary Tree Right Side View

Updated

TL;DR: Return the last node of every level of the tree. Walk the tree level by level with a queue, or go right first with DFS and keep the first node seen at each new depth.

Problem

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

Example 1

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Example 2

Input: root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]

Example 3

Input: root = [1,null,3]
Output: [1,3]

Example 4

Input: root = []
Output: []

Constraints

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

Constraints that matter

  • At most 100 nodes means even an O(n^2) scan finishes instantly, so a repeated-search brute force is legal here. The interview still expects O(n).
  • Node values lie in [-100, 100], so 0 and negative values are valid. Never use a falsy check or a sentinel like 0 or -1 to mean not found.
  • The tree can be empty (0 nodes), so the root itself can be null and the answer is an empty list.
  • Height is at most 100, so recursive DFS cannot overflow the stack in any of the six languages.

View on LeetCode

Hints

Hint 1

The view from the right shows exactly one node per depth: the rightmost node at that depth.

Hint 2

You need one value per depth.

Solution

Intuition

The view from the right shows exactly one node per depth: the rightmost node at that depth. That is the whole problem. Once you phrase it as one answer per level, the pattern is level order traversal.

It is like a row of mailboxes, one per floor, where the floor number is the depth. The result list is that row of mailboxes, and a right-first walk through the building drops a note in a mailbox only when it is empty, so the first person to reach each floor from the right leaves the note and everyone later on that floor is ignored.

A common first guess is to follow right pointers from the root. That fails when the left subtree is deeper. In the tree [1,2,3,4,null,null,null,5], node 3 has no children, so the nodes 4 and 5 on the left side show up below it. The right edge of the picture is not the right spine of the tree.

There are two clean ways to get one node per level. With BFS, you process each level left to right and keep the last node. With DFS, you visit the right child before the left child and record a node only when its depth is new. The first node to reach a depth in right-first order is the rightmost one at that depth.

Both work for the same reason. Depth decides which slot in the answer a node can fill, and position within the level decides who wins that slot. Pick the winner rule (last in BFS, first in right-first DFS) and each level yields exactly one value.

Watch the pattern animation

Worked example

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: Level 0 holds only 1. Level 1 holds 2 and 3, and 3 is on the right. Level 2 holds 5 and 4, and 4 is on the right. So you see 1, 3, 4 from top to bottom.

Approach 1: Brute force: search the whole tree once per depth

You need one value per depth. The most direct way is to ask, for each depth d starting at 0, "what is the rightmost node at depth d?" and answer each question with a fresh search from the root.

To answer one question, walk down from the root and count depth. At depth d, return the node. At every step try the right child first, then the left.

The first hit is the rightmost node at that depth. If the search returns nothing, the tree has no nodes that deep, so stop.

Steps

  1. Start with an empty result list and depth d = 0.
  2. Call find(root, d), which returns the rightmost value at depth d, or nothing if no node is that deep.
  3. In find, return null when the node is null, and return the node's value when d is 0.
  4. Otherwise call find on the right child with d - 1. If it finds something, return it.
  5. If the right side found nothing, return find on the left child with d - 1.
  6. If find returns nothing for the root, stop. Otherwise append the value, increment d and repeat.

Dry run

Tree [1,2,3,null,5,null,4], so 1 has children 2 and 3, node 2 has right child 5, and node 3 has right child 4.

  • d = 0: find(1, 0) returns 1. Result [1].
  • d = 1: find(1, 1) goes right to node 3 with d = 0 and returns 3. Result [1,3].
  • d = 2: find(1, 2) goes right to 3 with d = 1, then right to 4 with d = 0 and returns 4. Result [1,3,4].
  • d = 3: find(1, 3) tries 3 then 4 and finds nothing, since 4 has no children. It then tries 2 then 5 and finds nothing. It returns nothing, so the loop stops.

The answer is [1,3,4].

Complexity

TimeO(n * h)
SpaceO(h)

Let n be the node count and h the height. Each call to find visits at most every node once, so one depth costs O(n). The loop runs h + 1 times, h successes and one final failure, so the total is O(n * h).

In a skewed tree h is close to n, which makes this O(n^2) in the worst case. Space is the recursion depth, at most h, plus the output list.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        d = 0
        while True:
            v = self.find(root, d)
            if v is None:
                break
            res.append(v)
            d += 1
        return res

    def find(self, node, d):
        # rightmost value at depth d below node, or None
        if node is None:
            return None
        if d == 0:
            return node.val
        r = self.find(node.right, d - 1)
        if r is not None:
            return r
        return self.find(node.left, d - 1)
Level Order Traversal pattern infographic for Binary Tree Right Side View

Solution pattern

Level Order Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: BFS level order, keep the last nodeLevel Order Traversal

What's slow: the brute force restarts from the root for every depth, so it re-walks the upper levels again and again. Finding depth 5 re-visits all nodes on depths 0 to 4 on the way down.

The insight that fixes it: a queue already hands you the tree one level at a time, left to right. Take a snapshot of the queue size at the start of each round. That count is exactly the number of nodes on the current level.

The last node you pop in that round is the rightmost one, so record it. Each node is touched once.

Steps

  1. Return an empty list if root is null.
  2. Put root in a queue and create an empty result list.
  3. While the queue is not empty, read its size into size. That is the current level.
  4. Pop size nodes in a loop. Push each node's left child, then its right child, when they exist.
  5. When the loop index is size - 1, append that node's value to the result.
  6. Return the result when the queue is empty.

Dry run

Tree [1,2,3,null,5,null,4].

  • Level 0: the queue is [1], size 1. Pop 1, push 2 and 3. It is the last in its level, so record 1.
  • Level 1: the queue is [2,3], size 2. Pop 2 (index 0), push 5. Pop 3 (index 1), push 4. Index 1 is the last, so record 3.
  • Level 2: the queue is [5,4], size 2. Pop 5 (index 0), no children. Pop 4 (index 1), no children. Record 4.
  • The queue is empty. The result is [1,3,4].

Complexity

TimeO(n)
SpaceO(w)

Let n be the node count and w the maximum width of any level. Every node is pushed once and popped once, each in O(1), so time is O(n). The queue holds at most two adjacent levels at once, which is O(w). For a complete tree w is about n / 2, so the worst case is O(n).

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        if root is None:
            return res
        queue = deque([root])
        while queue:
            size = len(queue)  # snapshot: nodes on this level
            for i in range(size):
                node = queue.popleft()
                if i == size - 1:
                    res.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return res

Approach 3: Right-first DFS with depthOptimal

What's slow: BFS is already O(n) in time, but its queue can hold a whole level, which is up to about n / 2 nodes. The answer only needs one node per level, so you are storing far more than you use.

The insight that fixes it: visit the right child before the left child and carry the depth down the recursion. The first node you reach at a new depth is the rightmost node at that depth, because everything to its right in that level was visited first and did not exist.

The result list length doubles as a record of the deepest level seen so far. If the depth equals the current list length, this node is the first at its depth, so append it. Memory is now the recursion stack, which is the tree height.

Steps

  1. Create an empty result list.
  2. Define dfs(node, depth). Return immediately if node is null.
  3. If depth equals the length of the result list, append node.val. No node at this depth has been seen yet.
  4. Call dfs(node.right, depth + 1) first.
  5. Then call dfs(node.left, depth + 1).
  6. Call dfs(root, 0) and return the result.

Dry run

Tree [1,2,3,null,5,null,4]. Right child always goes first.

StepVisit (depth)Result lengthActionResult
11 (0)0depth 0 equals 0, append[1]
23 (1)1depth 1 equals 1, append[1,3]
34 (2)2depth 2 equals 2, append[1,3,4]
44's children (3)3both null, return[1,3,4]
53's left (2)3null, return[1,3,4]
62 (1)3depth 1 is not 3, skip[1,3,4]
75 (2)3depth 2 is not 3, skip[1,3,4]
85's children, 2's left3all null, return[1,3,4]

Nodes 2 and 5 are on the left, and levels 1 and 2 were already filled by 3 and 4. The answer is [1,3,4].

Complexity

TimeO(n)
SpaceO(h)

Let n be the node count and h the tree height. The recursion visits each node exactly once and does O(1) work per visit, so time is O(n). The call stack never exceeds h + 1 frames, and the result list has one entry per level, at most h + 1. So extra space is O(h), which is O(log n) for a balanced tree and O(n) for a skewed one.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res = []

        def dfs(node, depth):
            if node is None:
                return
            # first node reached at this depth is the rightmost
            if depth == len(res):
                res.append(node.val)
            dfs(node.right, depth + 1)
            dfs(node.left, depth + 1)

        dfs(root, 0)
        return res

Common mistakes

  • Following only node = node.right from the root. This misses left-subtree nodes that sit below the right spine. Handle every level, not only the right edge.
  • Writing for i in range(len(queue)) in a way that re-reads the size each time, such as while i < queue.size() in Java or C++. The queue grows as you push children and the level boundary shifts. Snapshot size before the inner loop starts.
  • Pushing the right child before the left child in BFS and still taking the last node of the level. The last node is then the leftmost. Push left first, or take the first node instead.
  • Writing if (!node) ... style checks on values, or using 0 as a not-found sentinel in the brute force. Values can be 0 and negative. Compare against null, not against falsy or a number.
  • Visiting left first in the DFS and recording on depth == len(res). That produces the left side view. Recurse into node.right before node.left.
  • Forgetting the empty tree. In BFS, queue.push(root) with a null root crashes on the first pop. Return an empty result when root is null.

Edge cases

  • Empty tree []: return an empty list.
  • Single node [5]: return [5].
  • Only left children, [1,2,null,3]: the answer is [1,2,3], since each left child is visible.
  • Left subtree deeper than the right, [1,2,3,4,null,null,null,5]: the answer is [1,3,4,5].
  • Node values of 0 or negative numbers: the value 0 must still be recorded, and no sentinel may collide with it.
  • Maximum size, 100 nodes in a single chain: recursion depth is 100, which is safe in every language.

Follow-ups interviewers ask

How would you return the left side view instead?
Flip the rule. In BFS, record the first node of each level (index 0). In DFS, visit the left child before the right child and keep the same depth equals length check. Nothing else changes.
Can you avoid the queue and use only O(h) extra space?
Yes, use the right-first DFS. It stores only the recursion stack, at most h + 1 frames, plus the output. For a balanced tree that is O(log n), against up to n / 2 for a BFS queue. For a skewed tree both are O(n).
What if the tree is too deep for recursion?
Run the DFS with an explicit stack of (node, depth) pairs. Push the left child first so the right child is popped first. Keep the same rule: append when depth equals the result length. Time stays O(n), and the stack depth is bounded by the height plus the siblings waiting.

Binary Tree Right Side View FAQ

What is the time complexity of Binary Tree Right Side View?

The BFS and right-first DFS solutions both run in O(n), where n is the number of nodes, because every node is visited once with constant work. The brute force that re-searches for each depth costs O(n * h), which is O(n^2) on a skewed tree.

Why use level order traversal for Binary Tree Right Side View?

The answer holds exactly one node per depth, and BFS hands you the tree one depth at a time in left-to-right order. The last node of each level is the rightmost one, so you need no extra bookkeeping beyond a size snapshot.

Can Binary Tree Right Side View be solved in O(1) extra space?

Not with ordinary traversal. Both BFS and DFS need a queue or a stack, and the output itself has up to h entries. A Morris-style threaded traversal can avoid the stack, but it modifies the tree temporarily and is not what interviewers expect here.

Why use DFS for Binary Tree Right Side View instead of BFS?

Right-first DFS uses O(h) stack space instead of a queue as wide as the widest level. It records a node only when its depth is new, so the first node seen per depth is the rightmost. Both are O(n) in time.

How does the solution handle a left subtree that is deeper than the right?

Levels that the right side does not reach have only left nodes. In BFS, the last node of such a level is a left-side node, and in DFS, the first node reaching that depth comes from the left subtree. Both therefore show those nodes.

Why does the Java or C# solution build a list first?

The starter code returns an int array, but the number of levels is unknown in advance. Collect values in a list, then copy them into an array of the final size at the end.

Asked at

See which companies ask this — Pro

Practise it