Binary Tree Right Side View
Medium · Trees
You are given the root of a binary tree. Imagine standing to the right of the tree looking at it from that side; return the values of the nodes you can see, ordered from the top of the tree to the bottom. A node is visible if it is the last (rightmost) node encountered at its depth level during a left-to-right scan.
Examples
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Why: Level 0 shows 1, level 1 shows 3 (rightmost of 2,3), level 2 shows 4 (rightmost of 5,4).
Input: root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]
Why: Each level's rightmost visible node from top to bottom is 1, 3, 4, then 5.
Input: root = []
Output: []
Why: An empty tree has no visible nodes.
Constraints
0 <= number of nodes <= 100, -100 <= Node.val <= 100
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Binary Tree Right Side View
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Binary Tree Right Side View. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.