AlgoLounge

Binary Tree Right Side View

medium

Given the root of a binary tree, return the values of the nodes you can see ordered from top to bottom when looking at the tree from the right side.

Examples

Example 1

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

The right side view shows nodes 1 (level 0), 3 (level 1), and 4 (level 2).

Example 2

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

Example 3

Input:  root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100

How the tests work: trees are written as level-order arrays — [1,null,2] is a root 1 with a right child 2. Your function receives real TreeNode objects.

TypeScript
Loading editor…
List of test cases (12)
Case 1
root = [1,2,3,null,5,null,4]
Case 2
root = [1,null,3]
Case 3
root = []
Case 4
root = [1,2,3,4]
Case 5
root = [1]
Case 6
root = [1,2,null,4,null,6]
Case 7
root = [1,2,3,4,5,6,7]
Case 8
root = [1,2,3,4,5,null,6,7,8]
Case 9
root = [1,null,2,null,3,null,4]
Case 10
root = [-100,-50,100,null,-25,75,null,null,50]
Case 11
root = [0,-1,1,-2,null,null,2]
Case 12
root = [5,3,7,1,4,6,8,null,2]