Skip to content
Optimal Lab

Trees · 114Medium

Binary Tree Right Side View

Given the root of a binary tree, imagine standing to its right. Return the values of the nodes visible from top to bottom.

Constraints

  • The tree holds 0 to 100 nodes.
  • -100 <= Node.val <= 100
  • INPUT FORMAT
  • `root` is a TreeNode object, not an array. The arrays in EXAMPLES are the level-order
  • serialization the platforms print — breadth-first, with `null` for a missing child. The
  • test runner builds a real tree from that array before calling your function.

Examples

rightSideView([1, 2, 3, null, 5, null, 4])  ->  [1, 3, 4]
rightSideView([1, null, 3])                 ->  [1, 3]
rightSideView(null)                         ->  []
rightSideView([1])                          ->  [1]   // a single node
rightSideView([1, 2, 3, 4, 5, 6, 7])        ->  [1, 3, 7]   // perfectly balanced
rightSideView([1, 2, null, 3, null, 4])     ->  [1, 2, 3, 4]  // a left-only tree shows all

Edge cases

  • An empty tree returns an empty array.
  • The visible node is the LAST at each level, which is not always a right child.
  • A left-only tree shows every one of its nodes.
Show the target complexity (spoiler)
Naive
Walking only right children is wrong — it misses left nodes whose level has no right
Target
O(n) time — a level-order BFS taking the final node of each level, or a DFS visiting right before left and recording the first node seen at each new depth.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/07-trees/114-binary-tree-right-side-view.js
./practice c 114

Stuck? Watch the pattern run