MediumPythonJavaScriptTypeScript
Binary Tree — Right Side View
Data StructuresTreesBFSDFS
Imagine standing on the right side of a binary tree. Return the values of the
nodes you can see, ordered from top to bottom — that is, the **last node of every
level**.
solve(levelOrder) receives the tree serialized level by level.
Examples
solve([1, 2, 3, null, 5, null, 4]) → [1, 3, 4]
solve([1, null, 3]) → [1, 3]
solve([1, 2, 3, 4]) → [1, 3, 4] // 4 is the only node on level three
solve([]) → []A node on the left can be visible when the right side is shorter, so "follow the
right children" is not enough.
Sample tests
Test #1Classic example
Input: [[1,2,3,null,5,null,4]]
Output: [1,3,4]
Test #2Only a right child
Input: [[1,null,3]]
Output: [1,3]
Test #3Empty tree
Input: [[]]
Output: []