# 199. Binary Tree Right Side View Leetcode Solution

## Binary Tree Right Side View Leetcode Problem :

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.

## Binary Tree Right Side View Leetcode Solution :

### Constraints :

• The number of nodes in the tree is in the range [0, 100].
• -100 <= Node.val <= 100

### Example 1:

• Input: root = [1,null,3]
• Output:  [1,3]
Intution : The code aims to find the right side view of a binary tree, which consists of the values of the nodes that are visible when looking at the tree from the right side. The idea is to perform a level-order traversal using a queue and keep track of the rightmost element at each level. Approach :
1. Initialization:
• Initialize an empty vector ans to store the right side view. Create a queue q for performing a level-order traversal.
1. Base Case:
• Check if the input root is nullptr. If true, return an empty vector, as there is no right side view.
1. Level-Order Traversal:
• Enqueue the root node into the queue q to start the traversal.
• Begin a while loop that continues until the queue is empty.
• Within the loop:
• Access the rightmost element of the current level by setting temp to the back of the queue (q.back()).
• Add the value of temp to the ans vector, representing the right side view.
• Determine the number of nodes at the current level (n) by getting the size of the queue.
• Iterate through all nodes at the current level using a nested loop:
• Enqueue the left child of the front element of the queue if it exists.
• Enqueue the right child of the front element of the queue if it exists.
• Dequeue the front element to move to the next node in the level.
• Repeat this process until all levels are traversed.
1. Return Result:
Once the traversal is complete, the ans vector contains the right side view of the binary tree.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others