Algo-Sim › Binary Trees & BST

Binary Tree Right Side View

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Standing to the right of the tree, you see the last node of every level: a level-order BFS that keeps each level’s last node.

Problem

Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered from top to bottom. On each level, a node hides every node to its left.

Constraints

Edge cases to test

Follow-up questions

Is there a DFS version?
Visit right before left and record the first node seen at each new depth: O(n) time, O(h) space.
How do you get the left view?
Take the first node of each level instead of the last.

Solution

Java

public List<Integer> rightSideView(TreeNode root) {
    List<Integer> view = new ArrayList<>();
    Queue<TreeNode> queue = new ArrayDeque<>();
    if (root != null) queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (i == size - 1) view.add(node.val);
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
    }
    return view;
}

Python

from collections import deque


def right_side_view(root):
    view = []
    queue = deque([root] if root else [])
    while queue:
        size = len(queue)
        for i in range(size):
            node = queue.popleft()
            if i == size - 1:
                view.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    return view

C++

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

class Solution {
  public:
    vector<int> rightSideView(TreeNode *root) {
        vector<int> view = {};
        deque<TreeNode *> queue = {};
        if (root != nullptr)
            queue.push_back(root);
        while (!queue.empty()) {
            int size = int(queue.size());
            for (int i = 0; i < size; i++) {
                TreeNode *node = queue.front();
                queue.pop_front();
                if (i == size - 1)
                    view.push_back(node->val);
                if (node->left != nullptr)
                    queue.push_back(node->left);
                if (node->right != nullptr)
                    queue.push_back(node->right);
            }
        }
        return view;
    }
};

More Binary Trees & BST problems