Search⌘ K
AI Features

Binary Tree Right Side View

Explore how to find the right-side view of a binary tree by applying depth-first search techniques. This lesson helps you understand how to identify which nodes are visible from the right, practicing key concepts in tree traversal and node visibility.

Statement

You are given a root of a binary tree that has n number of nodes. You have to return the right-side view in the form of a list.

A right-side view of a binary tree is the data of the nodes that are visible when the tree is viewed from the right side.

Constraints:

  • 00 \leq n 100\leq 100
  • 100-100 \leq Node.data 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Binary Tree Right Side View

1.

What will be the output of the following tree?

      ______ 1 ______ 
     |               |
     2 _           _ 3  
        |         |
      _ 4 _       5 
     |     |  
     6     7  
A.

[1, 3, 5, 7]

B.

[1, 3, 5]

C.

[1, 4, 5, 7]

D.

[1, 2, 3, 5]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Need a nudge?

Explore these hints—each one is designed to guide you a step closer to the solution.

C++
usercode > main.cpp
// Definition for a binary tree node
// template<class T>
// class TreeNode {
// public:
// T data;
// TreeNode<T>* left;
// TreeNode<T>* right;
// TreeNode(const T data) : data(data), left(nullptr), right(nullptr) {}
// };
// Function to get the right side view of a binary tree
std::vector<int> RightSideView(TreeNode<int>* root) {
// Replace this placeholder return statement with your code
return {};
}
Binary Tree Right Side View