Meta — Binary Tree Right Side View (BFS Level Order)

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem (Meta Trees Classic)

Given a binary tree, return the values of nodes visible from the right side (rightmost node at each depth).

Example:

    11
   / \
  2   33
   \   \
    5   44
[1, 3, 4]

Solutions

Python — BFS

from collections import deque

def rightSideView(root):
    if not root: return []
    res, q = [], deque([root])
    while q:
        level_size = len(q)
        for i in range(level_size):
            node = q.popleft()
            if i == level_size - 1:
                res.append(node.val)
            if node.left: q.append(node.left)
            if node.right: q.append(node.right)
    return res

Python — DFS (right-first preorder)

def rightSideView(root):
    res = []
    def dfs(node, depth):
        if not node: return
        if depth == len(res):
            res.append(node.val)
        dfs(node.right, depth + 1)
        dfs(node.left, depth + 1)
    dfs(root, 0)
    return res

JavaScript

function rightSideView(root) {
    if (!root) return [];
    const res=[], q=[root];
    while(q.length){
        const n=q.length; let last;
        for(let i=0;i<n;i++){const node=q.shift();last=node.val;if(node.left)q.push(node.left);if(node.right)q.push(node.right);}
        res.push(last);
    }
    return res;
}

Java

import java.util.*;
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> res=new ArrayList<>(); if(root==null)return res;
    Queue<TreeNode> q=new LinkedList<>(); q.offer(root);
    while(!q.isEmpty()){int n=q.size();TreeNode last=null;for(int i=0;i<n;i++){last=q.poll();if(last.left!=null)q.offer(last.left);if(last.right!=null)q.offer(last.right);}res.add(last.val);}
    return res;
}

C++

#include <queue>
#include <vector>
using namespace std;
vector<int> rightSideView(TreeNode* root) {
    if(!root) return {};
    vector<int> res; queue<TreeNode*> q; q.push(root);
    while(!q.empty()){int n=q.size(); TreeNode* last;for(int i=0;i<n;i++){last=q.front();q.pop();if(last->left)q.push(last->left);if(last->right)q.push(last->right);}res.push_back(last->val);}
    return res;
}

C

/* C: BFS with array-based queue, track last node per level */

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro