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.cs
TreeNode.cs
using System;
using System.Collections.Generic;
using System.Linq;
class Solution {
public static List<int> rightSideView(TreeNode root) {
// write your code here
return new List<int>();
}
}
Right-Side View of Binary Tree

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.cs
TreeNode.cs
using System;
using System.Collections.Generic;
class Solution {
public static void DFS(TreeNode node, int level, List<int> rightside) {
if (level == rightside.Count)
rightside.Add(node.val);
if (node.right != null)
DFS(node.right, level + 1, rightside);
if (node.left != null)
DFS(node.left, level + 1, rightside);
}
public static List<int> rightSideView(TreeNode root) {
List<int> rightside = new List<int>();
if (root == null) return rightside;
DFS(root, 0, rightside);
return rightside;
}
public static void Main(){
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
root.right.right.left = new TreeNode(8);
Console.WriteLine("[{0}]", string.Join(", ", rightSideView(root)));
}
}
Right-Side View of Binary Tree

Complexity measures

Time Complexity Space
...