Binary Tree Right Side View – 199. LeetCode


The Binary Tree Right Side View problem asks us to return the nodes that are visible when a binary tree is viewed from its right side. Imagine standing to the right of a tree and looking at it: you can only see the rightmost nodes of each level. This problem is a great way to understand tree traversal patterns and how to prioritize nodes in a specific direction.


Optimal Approach: Level-Order Traversal with BFS

1. Data Structure: Use a queue for level-order traversal (BFS).

2. Pattern: This algorithm uses the breadth-first search (BFS) pattern. By processing nodes level by level and storing only the rightmost node of each level, we directly extract the visible nodes.

• BFS ensures that all nodes of a level are processed before moving to the next.

• The last node encountered in each level is the rightmost node, making it straightforward to capture the right-side view.

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) return new ArrayList<Integer>();

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        List<Integer> result = new ArrayList();
        while (!q.isEmpty()) {
            int size = q.size();

            for (int i = 0; i < size; ++i) {
                TreeNode node = q.poll();

                // if it's the rightmost element
                if (i == size - 1) {
                    result.add(node.val);
                }

                // add child nodes in the queue
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
        }
        return result;
    }
}

Step 1: Handle the Empty Tree Case

if (root == null) return new ArrayList<Integer>();
  • Handles edge cases where the input tree is empty to prevent null point exceptions.

Step 2: Initialize the Queue and Result List

Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
List<Integer> result = new ArrayList<>();
  • Initialize a queue to hold nodes for level-order traversal.
  • Add the root node to the queue.
  • Store results in a list.
  • BFS is ideal for level-by-level traversal, and a queue is the best data structure for this purpose.

Step 3: Traverse the Tree Level by Level

while (!q.isEmpty()) {
    int size = q.size();
  • The while loop continues until the queue is empty, indicating all nodes have been processed.
  • Stores the current level’s size to iterate through all nodes at that level.

Step 4: Process Each Node in the Current Level

for (int i = 0; i < size; ++i) {
    TreeNode node = q.poll();
  • Iterates overall nodes in the current level (for loop runs size times).
  • Removes the front node from the queue using q.poll() and stores it in node.

Step 5: Add the Rightmost Node to the Result

if (i == size - 1) {
    result.add(node.val);
}
  • Checks if the current node is the rightmost node in the level (i == size – 1_.
  • Adds the node’s value to the result list.

Step 6: Add the Current Node’s Children to the Queue

if (node.left != null) {
    q.offer(node.left);
}
if (node.right != null) {
    q.offer(node.right);
}
  • Adds the left child of the current node to the queue if it exists.
  • Add the right child of the current node to the queue if it exists.
  • This step ensures BFS processes all nodes level by level.

Step 7: Return

return result;
  • Retuns the result list containing the rightmost nodes from each level.

Why This Code Works


This implementation leverages BFS to traverse the tree level by level, efficiently identifying the rightmost node of each level and collecting it in the result list. The use of a queue ensures proper level-order traversal, and the code handles edge cases like empty trees gracefully. By adhering to best practices in readability, efficiency, and correctness, this solution is well-suited for both interview settings and real-world applications.

Leave a Reply

Your email address will not be published. Required fields are marked *