Binary Tree Right Side View

Try to solve the Binary Tree Right Side View problem.

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#

Created with Fabric.js 3.6.6 1 2 3 4 5 6 7 8 9

1 of 3

Created with Fabric.js 3.6.6 1 2 3 4 5 6 7

2 of 3

Created with Fabric.js 3.6.6 1 2 3 4 7 5 6

3 of 3

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]

Question 1 of 30 attempted

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.

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

Return an empty list if the root is NULL.

Initialize a list to store the result. Apply depth-first search starting from the root.

At each visited node, if the length of the list is equal to the current tree level, then add the data of the node to the list.

Iterate over the child nodes of the current node (first the right child, then the left child). For each child, call DFS recursively.

After the DFS is completed, return the list.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > main.py
Input #1
%0 node_1 1 node_2 2 node_1->node_2 node_3 3 node_1->node_3 node_6 4 node_3->node_6 node_7 5 node_3->node_7
Visualization for Input #1
Binary Tree Right Side View

Solution: Maximum Depth of Binary Tree

Solution: Binary Tree Right Side View