AlgoMaster Logo

Binary Tree Right Side View

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Level Order Traversal

Intuition:

The idea is to perform a level order traversal (BFS) of the tree. During the traversal, record the last node you encounter at each level, as that is the node visible from the right side for that level.

Code:

2. DFS Preorder Traversal

Intuition:

We can use a modified DFS where we always attempt to visit the right child before the left child. This way, the first time we visit a new depth level, it's guaranteed to be the rightmost element. Store the value of such a node if the current depth is equal to the size of the result list.

Code: