Binary Tree Right Side View

Understand and solve the interview question "Binary Tree Right Side View".

Description

You are given a binary tree T. Imagine you are standing to the right of it; you have to return the value of the nodes you can see from top to bottom.

You have to return the rightmost nodes on their respective levels in the form of an array.

Let’s discuss an example below:

Coding exercise

main.py
TreeNode.py
from TreeNode import *
def right_side_view(root):
# write your code here
pass
Binary tree right side view

Solution

We can use a depth-first search (DFS) to solve this problem. The intuition here is to traverse the tree level by level recursively, starting from the rightmost node for each recursive call.

Let’s review the implementation below:

main.py
TreeNode.py
from TreeNode import *
def right_side_view(root):
if root is None:
return []
rightside = []
def DFS(node: TreeNode, level: int) -> None:
if level == len(rightside):
rightside.append(node.val)
for child in [node.right, node.left]:
if child:
DFS(child, level + 1)
DFS(root, 0)
return rightside
# Driver Code
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4);
root.left.right = TreeNode(5);
root.right.left = TreeNode(6);
root.right.right = TreeNode(7);
root.right.right.left = TreeNode(8);
print(right_side_view(root))
Binary tree right side view

Complexity measures

Time Complexity
...