Problem Description
Given the root of a binary tree, imagine yourself standing on the right side of it and return the values of the nodes you can see ordered from top to bottom.
Key Insights
- The problem is essentially about capturing the last node at each level (or the rightmost node) in a binary tree.
- A Breadth-First Search (BFS) approach naturally works by processing nodes level by level.
- Alternatively, Depth-First Search (DFS) can be adapted by prioritizing the right subtree first, ensuring that the first node encountered at each depth is the visible one.
- The number of nodes is capped at 100, so both approaches are efficient.
Space and Time Complexity
Time Complexity: O(n) - we visit every node in the tree.
Space Complexity: O(n) - in the worst case, the queue (or call stack for DFS) may hold all nodes of the tree.
Solution
We can solve this problem using BFS (level-order traversal). The idea is to traverse the tree level by level using a queue. For each level, the last element added to the level represents the rightmost view from that level. We then append that element’s value to our result list.
Alternatively, a DFS approach can be used where we visit the right subtree first. By keeping track of the current depth and checking if it’s the first time we’ve encountered this depth, we can add the first node visited at that depth (which will be the rightmost one) to the result.
In both approaches, appropriate data structures (a queue for BFS or recursion with a list for DFS) are used to store nodes and track the traversal state.