LogIn
I don't have account.
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
Adℹ

How to Find the Right View of a Binary Tree

DevSniper
47 Views

#tree

#binary-tree

#b-tree

#treemap

#depth-first-search

#breadth-first-search

Amazon Pay offer
Adℹ

Here's a mistake that's almost too easy to make: you've just solved left view of a binary tree, the interviewer nods and asks for right view next and since the two problems look so similar you reach for the same code, flip a comment or two and submit it. Except if you didn't actually flip the traversal direction, you've just handed back the left view a second time, dressed up as the answer to a different question. This article walks through exactly that trap and how to build a right view solution that's correct for the reason it should be, not by accident.

Problem Statement

You are given the root of a binary tree. Imagine standing to the right of the tree and looking straight across the right view is the set of nodes you'd actually be able to see from that angle.

More precisely: for every level of the tree, the right view keeps only the node that's furthest to the right at that level. Any other node at that same level, hidden behind it from this angle, is left out.

Given the root of a binary tree, return its right view as a list of values, ordered from the topmost level to the bottommost.

For example, for a tree shaped like this:

                  100
                /      \
              200        300
             /              \
           400                500
             \                /
             600            700

The right view is:

100, 300, 500, 700

Understanding the Problem First

Right view groups nodes by level (depth), exactly like left view does it does not involve horizontal distance at all, so it's a different kind of problem from top view or bottom view. The only thing that changes compared to left view is which node wins at each level: instead of the leftmost node, we want the rightmost one.

For the tree above:

  • Depth 0: just 100.
  • Depth 1: 200 and 300. 300 sits further right, so it wins.
  • Depth 2: 400 and 500. 500 sits further right, so it wins.
  • Depth 3: 600 and 700. 600 descends from 400 (on the left side of the tree) while 700 descends from 500 (on the right side), so 700 wins.

So the problem comes down to: for every depth, find the rightmost node, then read those winners off from the shallowest depth to the deepest. That single flipped word leftmost vs. rightmost is deceptively small on paper, but as we're about to see, it needs to be reflected consistently in every part of the solution, not just the final comparison.

Setting Up the Tree

We'll use the tree from above throughout this article.

class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }
}
public class SampleTree {
    public static TreeNode build() {
        TreeNode n100 = new TreeNode(100);
        TreeNode n200 = new TreeNode(200);
        TreeNode n300 = new TreeNode(300);
        TreeNode n400 = new TreeNode(400);
        TreeNode n500 = new TreeNode(500);
        TreeNode n600 = new TreeNode(600);
        TreeNode n700 = new TreeNode(700);

        n100.left = n200;
        n100.right = n300;
        n200.left = n400;
        n300.right = n500;
        n400.right = n600;
        n500.left = n700;

        return n100;
    }
}

Approach 1: The Naive Attempt (and How It Secretly Stays Left View)

Suppose you've already solved left view and the trick you landed on was: run a DFS, visit left before right and record a node into a depth-keyed map only the first time that depth is reached. That worked because visiting left before right guarantees the first node reached at any depth is the leftmost one.

Now, for right view, it's tempting to just reuse that exact same "first occurrence wins" logic, assuming the depth-tracking part is the important bit and the direction doesn't really matter. It does. If the traversal still visits left before right, "first occurrence per depth" still finds the leftmost node every time the goal changed, but the traversal order that made the old logic correct never did.

Tracing Through It

A standard preorder DFS (root, then left subtree, then right subtree) visits our tree in this order:

100 → 200 → 400 → 600 → 300 → 500 → 700

Recording a value only the first time each depth is reached:

Visit Node Depth Already claimed? Map after this step
1 100 0 no → add {0: 100}
2 200 1 no → add {..., 1: 200}
3 400 2 no → add {..., 2: 400}
4 600 3 no → add {..., 3: 600}
5 300 1 yes → skip unchanged
6 500 2 yes → skip unchanged
7 700 3 yes → skip unchanged

The naive output is:

100, 200, 400, 600

That list isn't nonsense it's a perfectly correct answer, just to the wrong question. It's the left view of this tree. The traversal never stopped visiting left before right, so "first occurrence" kept finding the leftmost node at every depth, exactly as before. Nothing about the depth-tracking logic was broken; the traversal direction underneath it just never got updated to match the new goal.

Approach 2: DFS With the Traversal Order Flipped (Correct)

The fix doesn't require new logic it requires flipping one decision: visit the right child before the left child. Once the traversal itself explores right-first at every branching point, "first occurrence per depth" starts finding the rightmost node instead, for exactly the same structural reason it used to find the leftmost one.

Tracing Through It

With right visited before left, our tree is now traversed in this order:

100 → 300 → 500 → 700 → 200 → 400 → 600

Recording a value only the first time each depth is reached:

Visit Node Depth Already claimed? Map after this step
1 100 0 no → add {0: 100}
2 300 1 no → add {..., 1: 300}
3 500 2 no → add {..., 2: 500}
4 700 3 no → add {..., 3: 700}
5 200 1 yes → skip unchanged
6 400 2 yes → skip unchanged
7 600 3 yes → skip unchanged

Reading the map from the shallowest depth to the deepest:

100, 300, 500, 700

the correct answer.

 
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};

void fillLevels(TreeNode* node, int depth, vector<int>& result) {
    if (node == nullptr) return;
    // The first node we reach at a given depth is the rightmost
    // one but only because we visit right before left below
    if (depth == (int)result.size()) {
        result.push_back(node->val);
    }
    fillLevels(node->right, depth + 1, result);
    fillLevels(node->left, depth + 1, result);
}

vector<int> rightView(TreeNode* root) {
    vector<int> result;
    fillLevels(root, 0, result);
    return result;
}

int main() {
    TreeNode* root = SampleTree::build();
    vector<int> result = rightView(root);
    for (int v : result) cout << v << " ";
    cout << endl;
    // Output: 100 300 500 700
    return 0;
}
 
using System;
using System.Collections.Generic;

public class RightViewDFS {
    public static List<int> RightView(TreeNode root) {
        List<int> result = new List<int>();
        FillLevels(root, 0, result);
        return result;
    }
    private static void FillLevels(TreeNode node, int depth, List<int> result) {
        if (node == null) return;
        // The first node we reach at a given depth is the rightmost
        // one but only because we visit right before left below
        if (depth == result.Count) {
            result.Add(node.val);
        }
        FillLevels(node.right, depth + 1, result);
        FillLevels(node.left, depth + 1, result);
    }
    public static void Main(string[] args) {
        TreeNode root = SampleTree.Build();
        List<int> result = RightView(root);
        Console.WriteLine(string.Join(", ", result));
        // Output: 100, 300, 500, 700
    }
}
 
import java.util.*;

public class RightViewDFS {
    public static List<Integer> rightView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        fillLevels(root, 0, result);
        return result;
    }
    private static void fillLevels(TreeNode node, int depth, List<Integer> result) {
        if (node == null) return;
        // The first node we reach at a given depth is the rightmost
        // one but only because we visit right before left below
        if (depth == result.size()) {
            result.add(node.val);
        }
        fillLevels(node.right, depth + 1, result);
        fillLevels(node.left, depth + 1, result);
    }
    public static void main(String[] args) {
        TreeNode root = SampleTree.build();
        System.out.println(rightView(root));
        // Output: [100, 300, 500, 700]
    }
}
 
def fill_levels(node, depth, result):
    if node is None:
        return
    # The first node we reach at a given depth is the rightmost
    # one but only because we visit right before left below
    if depth == len(result):
        result.append(node.val)
    fill_levels(node.right, depth + 1, result)
    fill_levels(node.left, depth + 1, result)

def right_view(root):
    result = []
    fill_levels(root, 0, result)
    return result

if __name__ == "__main__":
    root = SampleTree.build()
    result = right_view(root)
    print(result)
    # Output: [100, 300, 500, 700]

Notice this is almost character-for-character the same code as a left view solution the only change is the order of the two recursive calls at the bottom. That similarity is exactly what makes the Approach 1 mistake so easy to make and exactly why it's worth understanding why the order matters instead of just memorizing "swap left and right."

Complexity

Value
Time O(n) every node is visited once and the depth check is a constant-time list-size comparison
Space O(h) for the recursion stack, where h is the tree's height

Approach 3: BFS / Level Order Traversal (Optimal)

BFS sidesteps the whole "which child do I visit first" question, because level boundaries are already explicit in a queue-based traversal. Since a level order traversal processes one full level at a time, left to right, the rightmost node at any level is simply the last node dequeued during that level's turn no traversal-direction decision to get backwards in the first place.

Tracing Through It

Processing the tree level by level:

Level Nodes in this level (left to right) Node taken for right view
0 100 100
1 200, 300 300
2 400, 500 500
3 600, 700 700

Final result, read top to bottom:

100, 300, 500, 700
 
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};

vector<int> rightView(TreeNode* root) {
    vector<int> result;
    if (root == nullptr) return result;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int levelSize = q.size();
        for (int i = 0; i < levelSize; i++) {
            TreeNode* current = q.front();
            q.pop();
            // The last node processed in this level is the rightmost one
            if (i == levelSize - 1) {
                result.push_back(current->val);
            }
            if (current->left != nullptr) {
                q.push(current->left);
            }
            if (current->right != nullptr) {
                q.push(current->right);
            }
        }
    }
    return result;
}

int main() {
    TreeNode* root = SampleTree::build();
    vector<int> result = rightView(root);
    for (int v : result) cout << v << " ";
    cout << endl;
    // Output: 100 300 500 700
    return 0;
}
 
using System;
using System.Collections.Generic;

public class RightViewBFS {
    public static List<int> RightView(TreeNode root) {
        List<int> result = new List<int>();
        if (root == null) return result;
        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        while (queue.Count > 0) {
            int levelSize = queue.Count;
            for (int i = 0; i < levelSize; i++) {
                TreeNode current = queue.Dequeue();
                // The last node processed in this level is the rightmost one
                if (i == levelSize - 1) {
                    result.Add(current.val);
                }
                if (current.left != null) {
                    queue.Enqueue(current.left);
                }
                if (current.right != null) {
                    queue.Enqueue(current.right);
                }
            }
        }
        return result;
    }
    public static void Main(string[] args) {
        TreeNode root = SampleTree.Build();
        List<int> result = RightView(root);
        Console.WriteLine(string.Join(", ", result));
        // Output: 100, 300, 500, 700
    }
}
 
import java.util.*;

public class RightViewBFS {
    public static List<Integer> rightView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode current = queue.poll();
                // The last node processed in this level is the rightmost one
                if (i == levelSize - 1) {
                    result.add(current.val);
                }
                if (current.left != null) {
                    queue.add(current.left);
                }
                if (current.right != null) {
                    queue.add(current.right);
                }
            }
        }
        return result;
    }
    public static void main(String[] args) {
        TreeNode root = SampleTree.build();
        System.out.println(rightView(root));
        // Output: [100, 300, 500, 700]
    }
}
 
from collections import deque

def right_view(root):
    result = []
    if root is None:
        return result
    queue = deque([root])
    while queue:
        level_size = len(queue)
        for i in range(level_size):
            current = queue.popleft()
            # The last node processed in this level is the rightmost one
            if i == level_size - 1:
                result.append(current.val)
            if current.left is not None:
                queue.append(current.left)
            if current.right is not None:
                queue.append(current.right)
    return result

if __name__ == "__main__":
    root = SampleTree.build()
    result = right_view(root)
    print(result)
    # Output: [100, 300, 500, 700]

Note that unlike the DFS version, this BFS solution enqueues children in the normal left-then-right order there's no need to flip anything, since we're picking the last node processed per level rather than relying on visiting order to determine "first."

Complexity

Value
Time O(n) every node is enqueued and dequeued exactly once
Space O(n) for the queue in the worst case, when the tree's widest level holds close to n / 2 nodes

Comparing All Approaches

Approach Time Complexity Space Complexity Core Idea
Naive DFS (buggy) O(n) O(h) Left-before-right traversal with "first occurrence wins" correctly finds the leftmost node per depth, which is left view, not right view
DFS with Traversal Flipped O(n) O(h) Visit right before left, then take the first occurrence per depth now correctly finds the rightmost node
BFS / Level Order Optimal O(n) O(n) Take the last node dequeued at each level directly no traversal-direction decision needed

n = number of nodes, h = height of the tree.

Just like left view, right view groups by depth rather than horizontal distance, so there's no need for a TreeMap or any sorting step here both correct solutions run in clean O(n), with no logarithmic overhead. The real risk in this problem isn't complexity, it's direction: DFS-based solutions are entirely dependent on visiting children in the correct order and it's easy to carry that assumption over incorrectly from a similar problem.

Key Takeaways

  1. Similar problems can share logic and still need a real change, not a relabel. The "first occurrence wins" trick is correct for both left and right view but only once it's paired with the traversal direction that actually matches the question being asked.
  2. A wrong answer that looks plausible is the hardest kind to catch. Approach 1 doesn't crash and doesn't look obviously broken it just quietly answers a different, equally valid-looking problem.
  3. BFS removes an entire class of "which order did I mean" bugs. Because level boundaries are explicit in a queue, there's no traversal-direction assumption to get backwards in the first place.
  4. When adapting a solution from a near-identical problem, isolate exactly which piece encoded the old assumption. Here, that piece was two lines of recursive calls everything else about the "first occurrence per depth" logic carried over correctly.

Frequently Asked Questions

1. What is the difference between right view and left view of a binary tree?

Both group nodes by depth and keep exactly one node per level, but left view keeps the leftmost node at each level while right view keeps the rightmost one. A DFS solution for one becomes a solution for the other only if the traversal's child-visiting order is also flipped.

2. Why does reusing left view code for right view sometimes still return the left view?

If only the "first occurrence per depth" comparison is copied over but the traversal still visits the left child before the right child, the first node reached at each depth remains the leftmost one the traversal order is what actually determines which side wins, not the comparison logic alone.

3. Does finding the right view require tracking horizontal distance?

No. Like left view, right view depends only on depth and left-to-right position within a level. Horizontal distance is only needed for top view and bottom view, which group nodes differently.

4. What is the time complexity of finding the right view of a binary tree?

Both the correct DFS approach (visiting right before left) and the BFS approach run in O(n) time, where n is the number of nodes. No TreeMap or sorting is required, since depth values are already sequential.

5. Is BFS or DFS better for solving right view?

Both run in O(n) time. BFS is often considered safer here because level boundaries are explicit, so there's no traversal-direction assumption to get wrong. The DFS approach is equally correct, but only once the right-before-left visiting order is deliberately chosen rather than left unchanged from a left view solution.

Related Articles

Responses (0)

Write a response

CommentHide Comments

No Comments yet.

"},"4":{"id":4,"name":"ZEBRONICS Blanc mouse ad","otherData":"{}","contentFormat":2,"content":"
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
"},"2":{"id":2,"name":"Crousal Ads","otherData":"{}","contentFormat":2,"content":"
Sponsored -34%
iQOO Amazon's Choice

iQOO Z10 Lite 5G — Cyber Green, 4GB RAM, 128GB Storage

Dimensity 6300 · 50MP Sony AI Camera · 6000 mAh · IP64

★★★★★ 4.0 (2,052) 500+ bought last month
₹18,997 M.R.P. ₹28,999Save ₹10,002
Buy Now
"},"1":{"id":1,"name":"Banner Ads","otherData":"{}","contentFormat":2,"content":"\n
\n \n \n \"Amazon\n \n
"}}},"blogDetails":{"isWriter":false,"likes":0,"isLikedByUser":false,"tagIds":[21,27,32,43,133,177,282,316,317],"tags":[{"id":21,"name":"Tree","maskingName":"tree","isFeatured":false},{"id":27,"name":"Binary Tree","maskingName":"binary-tree","isFeatured":false},{"id":32,"name":"B-Tree","maskingName":"b-tree","isFeatured":false},{"id":43,"name":"HashMap","maskingName":"hashmap","isFeatured":true},{"id":133,"name":"Coding Problems","maskingName":"coding-problems","isFeatured":true},{"id":177,"name":"DSA","maskingName":"dsa","isFeatured":true},{"id":282,"name":"TreeMap","maskingName":"treemap","isFeatured":false},{"id":316,"name":"DFS","maskingName":"depth-first-search","isFeatured":false},{"id":317,"name":"BFS","maskingName":"breadth-first-search","isFeatured":false}],"comments":[],"bookmark":{"isBookmarked":false,"count":0},"author":{"userId":"MjlfNF84LVsyXTJuLXRDX0FOZ2VfX0l0","name":"DevSniper"},"viewCount":46,"showBannerImage":false,"seoTags":"Right View of Binary Tree, binary tree right view, right view of binary tree DFS, right view of binary tree BFS, binary tree interview questions, tree traversal algorithms, level order traversal, preorder traversal, DFS tree traversal, BFS tree traversal, binary tree problems, DSA tree problems, rightmost node at each level, tree view algorithms, coding interview preparation, data structures and algorithms, binary tree coding questions, recursive tree traversal, tree interview questions, solve right view binary tree","content":"

Here's a mistake that's almost too easy to make: you've just solved left view of a binary tree, the interviewer nods and asks for right view next and since the two problems look so similar you reach for the same code, flip a comment or two and submit it. Except if you didn't actually flip the traversal direction, you've just handed back the left view a second time, dressed up as the answer to a different question. This article walks through exactly that trap and how to build a right view solution that's correct for the reason it should be, not by accident.

\n

Problem Statement

\n

You are given the root of a binary tree. Imagine standing to the right of the tree and looking straight across the right view is the set of nodes you'd actually be able to see from that angle.

\n

More precisely: for every level of the tree, the right view keeps only the node that's furthest to the right at that level. Any other node at that same level, hidden behind it from this angle, is left out.

\n

Given the root of a binary tree, return its right view as a list of values, ordered from the topmost level to the bottommost.

\n

For example, for a tree shaped like this:

\n
                  100\n                /      \\\n              200        300\n             /              \\\n           400                500\n             \\                /\n             600            700\n
\n

The right view is:

\n
100, 300, 500, 700\n
\n

Understanding the Problem First

\n

Right view groups nodes by level (depth), exactly like left view does it does not involve horizontal distance at all, so it's a different kind of problem from top view or bottom view. The only thing that changes compared to left view is which node wins at each level: instead of the leftmost node, we want the rightmost one.

\n

For the tree above:

\n\n

So the problem comes down to: for every depth, find the rightmost node, then read those winners off from the shallowest depth to the deepest. That single flipped word leftmost vs. rightmost is deceptively small on paper, but as we're about to see, it needs to be reflected consistently in every part of the solution, not just the final comparison.

\n

Setting Up the Tree

\n

We'll use the tree from above throughout this article.

\n
class TreeNode {\n    int val;\n    TreeNode left, right;\n\n    TreeNode(int val) {\n        this.val = val;\n    }\n}\n
\n
public class SampleTree {\n    public static TreeNode build() {\n        TreeNode n100 = new TreeNode(100);\n        TreeNode n200 = new TreeNode(200);\n        TreeNode n300 = new TreeNode(300);\n        TreeNode n400 = new TreeNode(400);\n        TreeNode n500 = new TreeNode(500);\n        TreeNode n600 = new TreeNode(600);\n        TreeNode n700 = new TreeNode(700);\n\n        n100.left = n200;\n        n100.right = n300;\n        n200.left = n400;\n        n300.right = n500;\n        n400.right = n600;\n        n500.left = n700;\n\n        return n100;\n    }\n}\n
\n

Approach 1: The Naive Attempt (and How It Secretly Stays Left View)

\n

Suppose you've already solved left view and the trick you landed on was: run a DFS, visit left before right and record a node into a depth-keyed map only the first time that depth is reached. That worked because visiting left before right guarantees the first node reached at any depth is the leftmost one.

\n

Now, for right view, it's tempting to just reuse that exact same \"first occurrence wins\" logic, assuming the depth-tracking part is the important bit and the direction doesn't really matter. It does. If the traversal still visits left before right, \"first occurrence per depth\" still finds the leftmost node every time the goal changed, but the traversal order that made the old logic correct never did.

\n

Tracing Through It

\n

A standard preorder DFS (root, then left subtree, then right subtree) visits our tree in this order:

\n
100 → 200 → 400 → 600 → 300 → 500 → 700\n
\n

Recording a value only the first time each depth is reached:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
VisitNodeDepthAlready claimed?Map after this step
11000no → add{0: 100}
22001no → add{..., 1: 200}
34002no → add{..., 2: 400}
46003no → add{..., 3: 600}
53001yes → skipunchanged
65002yes → skipunchanged
77003yes → skipunchanged
\n
\n

The naive output is:

\n
100, 200, 400, 600\n
\n

That list isn't nonsense it's a perfectly correct answer, just to the wrong question. It's the left view of this tree. The traversal never stopped visiting left before right, so \"first occurrence\" kept finding the leftmost node at every depth, exactly as before. Nothing about the depth-tracking logic was broken; the traversal direction underneath it just never got updated to match the new goal.

\n

Approach 2: DFS With the Traversal Order Flipped (Correct)

\n

The fix doesn't require new logic it requires flipping one decision: visit the right child before the left child. Once the traversal itself explores right-first at every branching point, \"first occurrence per depth\" starts finding the rightmost node instead, for exactly the same structural reason it used to find the leftmost one.

\n

Tracing Through It

\n

With right visited before left, our tree is now traversed in this order:

\n
100 → 300 → 500 → 700 → 200 → 400 → 600\n
\n

Recording a value only the first time each depth is reached:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
VisitNodeDepthAlready claimed?Map after this step
11000no → add{0: 100}
23001no → add{..., 1: 300}
35002no → add{..., 2: 500}
47003no → add{..., 3: 700}
52001yes → skipunchanged
64002yes → skipunchanged
76003yes → skipunchanged
\n
\n

Reading the map from the shallowest depth to the deepest:

\n
100, 300, 500, 700\n
\n

the correct answer.

\n
 \n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode* left;\n    TreeNode* right;\n    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}\n};\n\nvoid fillLevels(TreeNode* node, int depth, vector<int>& result) {\n    if (node == nullptr) return;\n    // The first node we reach at a given depth is the rightmost\n    // one but only because we visit right before left below\n    if (depth == (int)result.size()) {\n        result.push_back(node->val);\n    }\n    fillLevels(node->right, depth + 1, result);\n    fillLevels(node->left, depth + 1, result);\n}\n\nvector<int> rightView(TreeNode* root) {\n    vector<int> result;\n    fillLevels(root, 0, result);\n    return result;\n}\n\nint main() {\n    TreeNode* root = SampleTree::build();\n    vector<int> result = rightView(root);\n    for (int v : result) cout << v << \" \";\n    cout << endl;\n    // Output: 100 300 500 700\n    return 0;\n}\n
 \nusing System;\nusing System.Collections.Generic;\n\npublic class RightViewDFS {\n    public static List<int> RightView(TreeNode root) {\n        List<int> result = new List<int>();\n        FillLevels(root, 0, result);\n        return result;\n    }\n    private static void FillLevels(TreeNode node, int depth, List<int> result) {\n        if (node == null) return;\n        // The first node we reach at a given depth is the rightmost\n        // one but only because we visit right before left below\n        if (depth == result.Count) {\n            result.Add(node.val);\n        }\n        FillLevels(node.right, depth + 1, result);\n        FillLevels(node.left, depth + 1, result);\n    }\n    public static void Main(string[] args) {\n        TreeNode root = SampleTree.Build();\n        List<int> result = RightView(root);\n        Console.WriteLine(string.Join(\", \", result));\n        // Output: 100, 300, 500, 700\n    }\n}\n
 \nimport java.util.*;\n\npublic class RightViewDFS {\n    public static List<Integer> rightView(TreeNode root) {\n        List<Integer> result = new ArrayList<>();\n        fillLevels(root, 0, result);\n        return result;\n    }\n    private static void fillLevels(TreeNode node, int depth, List<Integer> result) {\n        if (node == null) return;\n        // The first node we reach at a given depth is the rightmost\n        // one but only because we visit right before left below\n        if (depth == result.size()) {\n            result.add(node.val);\n        }\n        fillLevels(node.right, depth + 1, result);\n        fillLevels(node.left, depth + 1, result);\n    }\n    public static void main(String[] args) {\n        TreeNode root = SampleTree.build();\n        System.out.println(rightView(root));\n        // Output: [100, 300, 500, 700]\n    }\n}\n
 \ndef fill_levels(node, depth, result):\n    if node is None:\n        return\n    # The first node we reach at a given depth is the rightmost\n    # one but only because we visit right before left below\n    if depth == len(result):\n        result.append(node.val)\n    fill_levels(node.right, depth + 1, result)\n    fill_levels(node.left, depth + 1, result)\n\ndef right_view(root):\n    result = []\n    fill_levels(root, 0, result)\n    return result\n\nif __name__ == \"__main__\":\n    root = SampleTree.build()\n    result = right_view(root)\n    print(result)\n    # Output: [100, 300, 500, 700]\n
\n

Notice this is almost character-for-character the same code as a left view solution the only change is the order of the two recursive calls at the bottom. That similarity is exactly what makes the Approach 1 mistake so easy to make and exactly why it's worth understanding why the order matters instead of just memorizing \"swap left and right.\"

\n

Complexity

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Value
TimeO(n) every node is visited once and the depth check is a constant-time list-size comparison
SpaceO(h) for the recursion stack, where h is the tree's height
\n
\n

Approach 3: BFS / Level Order Traversal (Optimal)

\n

BFS sidesteps the whole \"which child do I visit first\" question, because level boundaries are already explicit in a queue-based traversal. Since a level order traversal processes one full level at a time, left to right, the rightmost node at any level is simply the last node dequeued during that level's turn no traversal-direction decision to get backwards in the first place.

\n

Tracing Through It

\n

Processing the tree level by level:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
LevelNodes in this level (left to right)Node taken for right view
0100100
1200, 300300
2400, 500500
3600, 700700
\n
\n

Final result, read top to bottom:

\n
100, 300, 500, 700\n
\n
 \n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode* left;\n    TreeNode* right;\n    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}\n};\n\nvector<int> rightView(TreeNode* root) {\n    vector<int> result;\n    if (root == nullptr) return result;\n    queue<TreeNode*> q;\n    q.push(root);\n    while (!q.empty()) {\n        int levelSize = q.size();\n        for (int i = 0; i < levelSize; i++) {\n            TreeNode* current = q.front();\n            q.pop();\n            // The last node processed in this level is the rightmost one\n            if (i == levelSize - 1) {\n                result.push_back(current->val);\n            }\n            if (current->left != nullptr) {\n                q.push(current->left);\n            }\n            if (current->right != nullptr) {\n                q.push(current->right);\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    TreeNode* root = SampleTree::build();\n    vector<int> result = rightView(root);\n    for (int v : result) cout << v << \" \";\n    cout << endl;\n    // Output: 100 300 500 700\n    return 0;\n}\n
 \nusing System;\nusing System.Collections.Generic;\n\npublic class RightViewBFS {\n    public static List<int> RightView(TreeNode root) {\n        List<int> result = new List<int>();\n        if (root == null) return result;\n        Queue<TreeNode> queue = new Queue<TreeNode>();\n        queue.Enqueue(root);\n        while (queue.Count > 0) {\n            int levelSize = queue.Count;\n            for (int i = 0; i < levelSize; i++) {\n                TreeNode current = queue.Dequeue();\n                // The last node processed in this level is the rightmost one\n                if (i == levelSize - 1) {\n                    result.Add(current.val);\n                }\n                if (current.left != null) {\n                    queue.Enqueue(current.left);\n                }\n                if (current.right != null) {\n                    queue.Enqueue(current.right);\n                }\n            }\n        }\n        return result;\n    }\n    public static void Main(string[] args) {\n        TreeNode root = SampleTree.Build();\n        List<int> result = RightView(root);\n        Console.WriteLine(string.Join(\", \", result));\n        // Output: 100, 300, 500, 700\n    }\n}\n
 \nimport java.util.*;\n\npublic class RightViewBFS {\n    public static List<Integer> rightView(TreeNode root) {\n        List<Integer> result = new ArrayList<>();\n        if (root == null) return result;\n        Queue<TreeNode> queue = new LinkedList<>();\n        queue.add(root);\n        while (!queue.isEmpty()) {\n            int levelSize = queue.size();\n            for (int i = 0; i < levelSize; i++) {\n                TreeNode current = queue.poll();\n                // The last node processed in this level is the rightmost one\n                if (i == levelSize - 1) {\n                    result.add(current.val);\n                }\n                if (current.left != null) {\n                    queue.add(current.left);\n                }\n                if (current.right != null) {\n                    queue.add(current.right);\n                }\n            }\n        }\n        return result;\n    }\n    public static void main(String[] args) {\n        TreeNode root = SampleTree.build();\n        System.out.println(rightView(root));\n        // Output: [100, 300, 500, 700]\n    }\n}\n
 \nfrom collections import deque\n\ndef right_view(root):\n    result = []\n    if root is None:\n        return result\n    queue = deque([root])\n    while queue:\n        level_size = len(queue)\n        for i in range(level_size):\n            current = queue.popleft()\n            # The last node processed in this level is the rightmost one\n            if i == level_size - 1:\n                result.append(current.val)\n            if current.left is not None:\n                queue.append(current.left)\n            if current.right is not None:\n                queue.append(current.right)\n    return result\n\nif __name__ == \"__main__\":\n    root = SampleTree.build()\n    result = right_view(root)\n    print(result)\n    # Output: [100, 300, 500, 700]\n
\n

Note that unlike the DFS version, this BFS solution enqueues children in the normal left-then-right order there's no need to flip anything, since we're picking the last node processed per level rather than relying on visiting order to determine \"first.\"

\n

Complexity

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Value
TimeO(n) every node is enqueued and dequeued exactly once
SpaceO(n) for the queue in the worst case, when the tree's widest level holds close to n / 2 nodes
\n
\n

Comparing All Approaches

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ApproachTime ComplexitySpace ComplexityCore Idea
Naive DFS (buggy)O(n)O(h)Left-before-right traversal with \"first occurrence wins\" correctly finds the leftmost node per depth, which is left view, not right view
DFS with Traversal FlippedO(n)O(h)Visit right before left, then take the first occurrence per depth now correctly finds the rightmost node
BFS / Level Order OptimalO(n)O(n)Take the last node dequeued at each level directly no traversal-direction decision needed
\n
\n

n = number of nodes, h = height of the tree.

\n

Just like left view, right view groups by depth rather than horizontal distance, so there's no need for a TreeMap or any sorting step here both correct solutions run in clean O(n), with no logarithmic overhead. The real risk in this problem isn't complexity, it's direction: DFS-based solutions are entirely dependent on visiting children in the correct order and it's easy to carry that assumption over incorrectly from a similar problem.

\n

Key Takeaways

\n
    \n
  1. Similar problems can share logic and still need a real change, not a relabel. The \"first occurrence wins\" trick is correct for both left and right view but only once it's paired with the traversal direction that actually matches the question being asked.
  2. \n
  3. A wrong answer that looks plausible is the hardest kind to catch. Approach 1 doesn't crash and doesn't look obviously broken it just quietly answers a different, equally valid-looking problem.
  4. \n
  5. BFS removes an entire class of \"which order did I mean\" bugs. Because level boundaries are explicit in a queue, there's no traversal-direction assumption to get backwards in the first place.
  6. \n
  7. When adapting a solution from a near-identical problem, isolate exactly which piece encoded the old assumption. Here, that piece was two lines of recursive calls everything else about the \"first occurrence per depth\" logic carried over correctly.
  8. \n
\n

Frequently Asked Questions

\n
\n

1. What is the difference between right view and left view of a binary tree?

\n

Both group nodes by depth and keep exactly one node per level, but left view keeps the leftmost node at each level while right view keeps the rightmost one. A DFS solution for one becomes a solution for the other only if the traversal's child-visiting order is also flipped.

\n

2. Why does reusing left view code for right view sometimes still return the left view?

\n

If only the \"first occurrence per depth\" comparison is copied over but the traversal still visits the left child before the right child, the first node reached at each depth remains the leftmost one the traversal order is what actually determines which side wins, not the comparison logic alone.

\n

3. Does finding the right view require tracking horizontal distance?

\n

No. Like left view, right view depends only on depth and left-to-right position within a level. Horizontal distance is only needed for top view and bottom view, which group nodes differently.

\n

4. What is the time complexity of finding the right view of a binary tree?

\n

Both the correct DFS approach (visiting right before left) and the BFS approach run in O(n) time, where n is the number of nodes. No TreeMap or sorting is required, since depth values are already sequential.

\n

5. Is BFS or DFS better for solving right view?

\n

Both run in O(n) time. BFS is often considered safer here because level boundaries are explicit, so there's no traversal-direction assumption to get wrong. The DFS approach is equally correct, but only once the right-before-left visiting order is deliberately chosen rather than left unchanged from a left view solution.

\n
\n

Related Articles

\n
\n

Bottom View of a Binary Tree

\n

Left View of a Binary Tree

\n

Top View of a Binary Tree

\n
","categoryId":177,"subCategoryId":177,"contentFormat":5,"blogId":207,"userId":"MjlfNF84LVsyXTJuLXRDX0FOZ2VfX0l0","title":"How to Find the Right View of a Binary Tree","url":"right-view-of-a-binary-tree","bannerImage":"","seoDescription":"Learn how to find the right view of a binary tree using DFS and BFS, with examples, code, complexity analysis and coding interview tips.","generatedOn":"2026-08-28T10:18:21","updatedOn":"2026-08-28T10:18:21"},"popularContents":[{"id":130,"title":"Rippling SDE-2 Interview Experience (4+ Years Experience) | Offer Received | Coding, LLD & System Design","url":"rippling-sde-2-interview-experience-4-years-experience-offer-received-coding-lld-system-design","description":null,"seoDescription":"Detailed Rippling SDE-2 interview experience with complete 5 rounds, coding questions, rules engine design, system design and preparation tips.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898639Z","viewCount":0},{"id":83,"title":"Uber SDE 2 Interview Experience (5 Rounds, Selected) - Complete DSA Questions with solution, System Design & Managerial Round","url":"uber-sde-2-interview-experience","description":null,"seoDescription":"Uber SDE 2 interview experience with 5 rounds, real DSA questions, system design, coding round, and preparation tips to crack Uber interviews.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898597Z","viewCount":0},{"id":34,"title":"System Design Deep Dive: 25 Essential Interview Questions","url":"system-design-deep-dive-25-essential-interview-questions","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898546Z","viewCount":0},{"id":118,"title":"JioHotstar Staff Software Engineer Interview Experience (Bangalore)","url":"jiohotstar-staff-software-engineer-interview-experience-bangalore","description":null,"seoDescription":"JioHotstar Staff Software Engineer interview experience covering Uber system design, API rate limiter LLD, leadership rounds, bar raiser and HR insights.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898618Z","viewCount":0},{"id":166,"title":"System Design Interview – BIGGEST Mistakes to Avoid","url":"system-design-interview-biggest-mistakes-to-avoid","description":null,"seoDescription":"Learn the biggest mistakes to avoid in a system design interview, from unclear requirements to poor trade-off analysis. Includes real-world cases, advanced insights and examples to help you ace your next system design interview.","contentType":2,"generatedOn":"2026-10-14T22:53:54.4892897Z","viewCount":0},{"id":171,"title":"Meesho SDE-1 Backend Interview Experience (Remote | 3 Round) - Rejected","url":"meesho-sde-1-backend-interview-experience-remote-3-round-rejected","description":null,"seoDescription":"Read a real Meesho SDE-1 Backend interview experience covering the online assessment, DSA interview, machine coding round, LLD questions and preparation tips.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898698Z","viewCount":0},{"id":135,"title":"Spinny SDE-1 Interview Experience (Selected)","url":"spinny-sde-1-interview-experience-selected","description":null,"seoDescription":"Spinny SDE-1 Interview Experience (Selected) | 4 Rounds Breakdown: Coding, LLD, Java, SQL + Real Interview Questions","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898659Z","viewCount":0},{"id":172,"title":"Google L4 Software Engineer III interview experience | Selected","url":"google-l4-software-engineer-iii-interview-experience-selected","description":null,"seoDescription":"Google L4 Software Engineer III interview experience with API design, Googlyness, route matching, graph coding rounds, follow-up questions and tips.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898716Z","viewCount":0},{"id":173,"title":"Uber SDE-2 Interview Experience : LLD, HLD, DSA & Hiring Manager Round","url":"uber-sde-2-interview-experience-lld-hld-dsa-hiring-manager-round","description":null,"seoDescription":"Read a real Uber SDE-2 interview experience covering DSA, low-level design, high-level system design, behavioral rounds, hiring freeze and key takeaways.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898775Z","viewCount":0},{"id":138,"title":"DSA Patterns for Coding Interviews: Complete LeetCode Roadmap (Beginner to Advanced)","url":"dsa-patterns-for-coding-interviews-complete-leetcode-roadmap-beginner-to-advanced","description":null,"seoDescription":"Master every LeetCode pattern for coding interviews. Learn Arrays, Sliding Window, Graphs, Dynamic Programming, Trees, Heaps and more with 250+ curated problem","contentType":5,"generatedOn":"2026-10-14T22:53:54.4898682Z","viewCount":0}],"latestContents":[{"id":219,"title":"6 Tools That Made My Life Easier as a Software Engineer","url":"6-tools-that-made-my-life-easier-as-a-software-engineer","description":null,"seoDescription":"The 6 developer tools I use daily as a software engineer: Git, VS Code, Docker, Postman, Chrome DevTools, and AI assistants, with real tips, mistakes, and trade","contentType":5,"generatedOn":"2026-10-14T22:53:54.4879896Z","viewCount":0},{"id":218,"title":"When Should a Business Use Multiple AI Agents Instead of One?","url":"when-should-a-business-use-multiple-ai-agents-instead-of-one","description":null,"seoDescription":"Single agent or multi-agent AI? Learn the 4 signals that justify splitting agents by knowledge, permissions, and risk, plus routing and handoff tips.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4879948Z","viewCount":0},{"id":216,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:53:54.4879967Z","viewCount":0},{"id":217,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:53:54.4879981Z","viewCount":0},{"id":215,"title":"What Happens When an AI Agent Doesn't Know the Answer?","url":"what-happens-when-an-ai-agent-doesnt-know-the-answer","description":null,"seoDescription":"Most AI agents fail quietly. They guess instead of saying \"I don't know.\" Here's how to design better fallback and human-handoff behavior.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4879993Z","viewCount":0},{"id":214,"title":"Greedy Algorithms Explained: How They Work, When They Fail and How to Use Them","url":"greedy-algorithms-explained-how-they-work-when-they-fail-and-how-to-use-them","description":null,"seoDescription":"Learn greedy algorithms step by step with C# code Dijkstra, Huffman coding, knapsack and MSTs plus when greedy fails and how to prove it's correct","contentType":5,"generatedOn":"2026-10-14T22:53:54.4880031Z","viewCount":0},{"id":213,"title":"Amazon SDE II Interview Experience (Bangalore, Selected) ~ Aug 2026","url":"amazon-sde-ii-interview-experience-bangalore-selected-aug-2026","description":null,"seoDescription":"Amazon SDE II interview experience from Bangalore covering 4 rounds, DSA, LLD, system design, Leadership Principles, coding questions and selection.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4880044Z","viewCount":0},{"id":212,"title":"How to Get 10x Better AI Answers Without Writing Better Prompts : 10 Proven Techniques","url":"how-to-get-10x-better-ai-answers-without-writing-better-prompts-10-proven-techniques","description":null,"seoDescription":"Get better AI answers without complex prompts. Learn 10 practical techniques using context, examples, tools, feedback, and verification.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4880056Z","viewCount":0},{"id":211,"title":"I Interviewed for a Microsoft SDE I Role. Here's Everything That Happened.","url":"i-interviewed-for-a-microsoft-sde-i-role-heres-everything-that-happened","description":null,"seoDescription":"My real Microsoft SDE I interview experience, all 4 rounds, the exact DSA problems with fully tested solutions, the WhatsApp system design round","contentType":5,"generatedOn":"2026-10-14T22:53:54.4880069Z","viewCount":0},{"id":140,"title":"PolicyBazaar Software Development Engineer (SDE) Interview Experience | DSA, Core CS & System Design","url":"policybazaar-software-development-engineer-sde-interview-experience-dsa-core-cs-system-design","description":null,"seoDescription":"Detailed PolicyBazaar SDE interview experience covering 3 rounds: DSA coding, core CS assessment and system design with key learnings and insights.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4880081Z","viewCount":0}],"relatedContents":[{"id":206,"title":"Left View of a Binary Tree: DFS and BFS Approaches Explained","url":"left-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the left view of a binary tree using DFS and BFS, with examples, code, complexity analysis, common mistakes and interview tips.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968245Z","viewCount":0},{"id":205,"title":"Top View of a Binary Tree Using BFS and DFS | Complete Guide","url":"top-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the top view of a binary tree using DFS and BFS with step-by-step explanations, examples, code, complexity analysis and interview insights.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968261Z","viewCount":0},{"id":201,"title":"Bottom View of a Binary Tree: DFS vs BFS Approach","url":"bottom-view-of-a-binary-tree-dfs-vs-bfs-approach","description":null,"seoDescription":"Learn to find the bottom view of a binary tree using horizontal distance. Compares a buggy DFS attempt, a fixed DFS and the optimal BFS solution in Java.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968275Z","viewCount":0},{"id":200,"title":" Longest Playlist With No Repeated Songs : Brute Force to Optimal","url":"longest-playlist-with-no-repeated-songs-brute-force-to-optimal","description":null,"seoDescription":"Find the longest playlist with no repeated songs using brute force, HashSet, and HashMap sliding window techniques, with Java code and dry runs.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968288Z","viewCount":0},{"id":90,"title":"Contain Virus : Deep, Intuitive & Fully Explained Guide","url":"contain-virus-deep-intuitive-fully-explained-guide","description":null,"seoDescription":"Contain Virus problem explained with DFS + greedy approach, step-by-step simulation, examples and optimized solutions for coding interviews.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968313Z","viewCount":0},{"id":37,"title":"Find the repeating and missing numbers","url":"find-the-repeating-and-missing-numbers","description":null,"seoDescription":"Find the repeating and missing numbers in an array from 1..n using brute force, hashmap, math and XOR, step-by-step explained with real-world use cases.","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968329Z","viewCount":0},{"id":27,"title":"4 Sum | Find Quads that add up to a target value","url":"4-sum-find-quads-that-add-up-to-a-target-value","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968346Z","viewCount":0},{"id":26,"title":"Top 50 Most Frequently Asked String Coding Problems (Interview Preparation )","url":"top-50-most-frequently-asked-string-coding-problems-interview-preparation","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968359Z","viewCount":0},{"id":25,"title":"Intersection of Two Sorted Arrays","url":"intersection-of-two-sorted-arrays","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:54.4968374Z","viewCount":0}]}}},"source":{"isMobile":false}}; window.__CLIENT_RENDER__ = false;