C# || Binary Tree Right Side View – How To Get Nodes Ordered Top To Bottom C#

The following is a module with functions which demonstrates how to get nodes in a binary tree ordered from top to bottom using C#.


1. Right Side View – Problem Statement

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.

Example 1:

Example 1


Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Example 2:


Input: root = [1,null,3]
Output: [1,3]

Example 3:


Input: root = []
Output: []


2. Right Side View – Solution

The following is a solution which demonstrates how to get right side nodes ordered from top to bottom.

This solution uses Depth First Search level order traversal to explore items at each level, and then adds the last node on every layer.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[1,3,4]
[1,3]
[]

Was this article helpful?
👍 YesNo

Leave a Reply