Bird
Raised Fist0
Interview Preptree-bfsmediumFacebookAmazonBloomberg

Binary Tree Right Side View

Choose your preparation mode4 modes available
📋
Problem

Imagine standing on the right side of a tall building and wanting to see which windows are visible on each floor. This problem asks you to find the nodes visible when looking at a binary tree from its right side.

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

The number of nodes in the tree is in the range [1, 10^5].-100 <= Node.val <= 100
Edge cases: Single node tree → output is the single node's valueAll nodes only have left children → output is all nodes in top-down orderAll nodes only have right children → output is all nodes in top-down order
</>
IDE
def rightSideView(root: Optional[TreeNode]) -> List[int]:public List<Integer> rightSideView(TreeNode root)vector<int> rightSideView(TreeNode* root)function rightSideView(root)
def rightSideView(root: Optional[TreeNode]) -> List[int]:
    # Write your solution here
    pass
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
using namespace std;

vector<int> rightSideView(TreeNode* root) {
    // Write your solution here
    return {};
}
function rightSideView(root) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: [1,2,5]Greedy approach picking leftmost node at each level instead of rightmost.✅ Traverse right child before left child in DFS or pick last node in BFS level traversal.
Wrong: [1,3]Off-by-one error in depth tracking causing last level nodes to be missed.✅ Ensure depth increments correctly and update rightmost node at each level accordingly.
Wrong: [1,2,3]Not handling skewed trees properly, missing nodes on one side.✅ Include checks for null children and traverse both left and right children.
Wrong: Exception or crashNo null root check causing runtime error on empty tree input.✅ Add base case to return empty list if root is null.
Wrong: Timeout or no outputExponential or repeated traversal causing TLE on large input.✅ Use O(n) BFS or DFS with level tracking to ensure linear time complexity.
✓
Test Cases
t1_01basic
Input{"root":[1,2,3,null,5,null,4]}
Expected[1,3,4]

At level 0, node 1 is visible; at level 1, node 3 is the rightmost; at level 2, node 4 is the rightmost visible node.

t1_02basic
Input{"root":[1,2,3,4,5,6,7]}
Expected[1,3,7]

Complete binary tree: rightmost nodes per level are 1 (root), 3 (right child), and 7 (rightmost leaf).

t2_01edge
Input{"root":null}
Expected[]

Empty tree has no visible nodes, so output is an empty list.

t2_02edge
Input{"root":[42]}
Expected[42]

Single node tree; the only node is visible from the right side.

t2_03edge
Input{"root":[1,2,null,3,null,4,null,5]}
Expected[1,2,3,4,5]

All nodes only have left children; right side view is all nodes top-down since no right children block view.

t3_01corner
Input{"root":[1,null,2,null,3,null,4,null,5]}
Expected[1,2,3,4,5]

All nodes only have right children; right side view is all nodes top-down.

t3_02corner
Input{"root":[1,2,3,4,null,null,5,null,6]}
Expected[1,3,5,6]

Tree where greedy approach picking first child per level fails; rightmost nodes are 1,3,5,6.

t3_03corner
Input{"root":[1,2,3,4,5,6,7,8,null,null,null,null,null,null,9]}
Expected[1,3,7,9]

Test for off-by-one errors in level tracking; rightmost nodes are 1,3,7,9.

t4_01performance
Input{"root":[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9,null,10,null,11,null,12,null,13,null,14,null,15,null,16,null,17,null,18,null,19,null,20,null,21,null,22,null,23,null,24,null,25,null,26,null,27,null,28,null,29,null,30,null,31,null,32,null,33,null,34,null,35,null,36,null,37,null,38,null,39,null,40,null,41,null,42,null,43,null,44,null,45,null,46,null,47,null,48,null,49,null,50,null,51,null,52,null,53,null,54,null,55,null,56,null,57,null,58,null,59,null,60,null,61,null,62,null,63,null,64,null,65,null,66,null,67,null,68,null,69,null,70,null,71,null,72,null,73,null,74,null,75,null,76,null,77,null,78,null,79,null,80,null,81,null,82,null,83,null,84,null,85,null,86,null,87,null,88,null,89,null,90,null,91,null,92,null,93,null,94,null,95,null,96,null,97,null,98,null,99,null,100]}
⏱ Performance - must finish in 2000ms

Right-skewed tree with n=100 nodes; O(n) BFS or DFS must complete within 2 seconds.

Practice

(1/5)
1. You are given a binary tree and asked to compute the average value of nodes on each level. Which algorithmic approach guarantees an optimal solution that processes nodes level-by-level and efficiently computes these averages?
easy
A. Depth-first search (DFS) without tracking levels, summing all nodes and dividing by total count.
B. Breadth-first search (BFS) using a queue to traverse nodes level-by-level, summing values per level and dividing by the number of nodes at that level.
C. Greedy approach that picks the maximum node value at each level and averages those maximums.
D. Dynamic programming that stores partial sums of subtrees and combines them bottom-up.

Solution

  1. Step 1: Understand the problem requires level-wise aggregation

    The problem asks for averages per level, so nodes must be grouped by their depth in the tree.
  2. Step 2: Identify BFS as the natural approach for level order traversal

    BFS uses a queue to process nodes level-by-level, allowing summing and counting nodes at each level before moving on.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    BFS naturally groups nodes by level, enabling correct average calculation [OK]
Hint: Level order traversal = BFS with queue [OK]
Common Mistakes:
  • Using DFS without level tracking loses level grouping
  • Greedy max per level ignores all other nodes
  • Bottom-up DP is unnecessary and complex here
2. You are given a binary tree and need to determine if it is symmetric around its center. Which approach best guarantees an optimal solution by comparing nodes in pairs using a queue and terminating early when asymmetry is detected?
easy
A. Recursive depth-first traversal comparing left subtree to left subtree
B. Dynamic programming storing subtree symmetry states bottom-up
C. Greedy traversal checking only the root and immediate children
D. Iterative breadth-first search using a queue to compare mirrored node pairs with early termination

Solution

  1. Step 1: Understand the problem requirement

    The problem requires checking if a tree is symmetric, which means the left subtree is a mirror reflection of the right subtree.
  2. Step 2: Identify the approach that compares mirrored nodes efficiently

    Using an iterative BFS with a queue to compare pairs of nodes from left and right subtrees simultaneously allows early detection of asymmetry and avoids unnecessary traversal.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Iterative BFS with paired nodes and early termination is optimal for symmetry check [OK]
Hint: Symmetry requires mirrored node pair comparison [OK]
Common Mistakes:
  • Comparing left subtree to left subtree instead of mirrored right subtree
  • Using greedy checks that miss deeper asymmetry
  • Assuming symmetry can be checked by root and immediate children only
3. The following code attempts to compute the average of levels in a binary tree. Identify the line containing the subtle bug that causes incorrect averages when the tree is empty or null.
medium
A. Line 2: Missing check for empty tree before initializing queue
B. Line 5: Incorrect initialization of level_sum to zero
C. Line 9: Using popleft() instead of pop() on queue
D. Line 13: Appending average without converting to float

Solution

  1. Step 1: Check for empty tree handling

    Code initializes queue with root without checking if root is None, causing queue to contain None.
  2. Step 2: Consequence of missing check

    When root is None, popleft() returns None, and accessing node.val causes an error.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Adding "if not root: return []" fixes the bug [OK]
Hint: Always check for empty input before queue initialization [OK]
Common Mistakes:
  • Forgetting empty tree check
  • Misusing queue methods
  • Integer division truncation (not here)
4. Consider this buggy BFS code for finding largest values in each tree row:
def largestValues(root):
    if not root:
        return []
    res = []
    queue = deque([root])
    while queue:
        level_max = float('-inf')
        for _ in range(len(queue)):
            node = queue.popleft()
            level_max = max(level_max, node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        res.append(level_max)
    return res
What subtle bug could cause incorrect results when running multiple test cases in the same environment?
medium
A. Not resetting the queue between test cases causing leftover nodes to be processed
B. Appending level_max before processing all nodes at the current level
C. Forgetting to check if node.left or node.right is None before appending
D. Using a global variable for res without clearing it before each call

Solution

  1. Step 1: Identify use of global variables

    If res is declared globally and not cleared before each call, results accumulate across tests.
  2. Step 2: Confirm other lines are correct

    Queue is local and reset per call; children are checked for None; level_max appended after level processed.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Global res not cleared -> incorrect cumulative results [OK]
Hint: Global variables must be reset between test runs [OK]
Common Mistakes:
  • Forgetting to clear global or static variables
  • Assuming local variables persist incorrectly
  • Misunderstanding queue initialization scope
5. What is the time complexity of the optimal iterative BFS approach using two queues for N-ary tree level order traversal, where n is the number of nodes in the tree?
medium
A. O(n) because each node is visited exactly once
B. O(n²) because each node's children are enqueued multiple times
C. O(n log n) due to sorting nodes at each level
D. O(n + m) where m is the maximum number of children per node

Solution

  1. Step 1: Identify operations per node

    Each node is enqueued and dequeued exactly once, and its children are iterated once.
  2. Step 2: Sum over all nodes

    Since total nodes are n, total operations scale linearly with n.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Traversal visits each node once -> O(n) time [OK]
Hint: BFS visits each node once, no repeated work [OK]
Common Mistakes:
  • Assuming children are enqueued multiple times causing O(n²)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard