noodleProblems/
Binary Tree Right Side View
#138

Binary Tree Right Side View

AlgorithmmediumTreeDepth First SearchBreadth First SearchBinary Tree

Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered top to bottom.

The visible node at each depth is the **last** node on that level (its rightmost node). Note a level's rightmost visible node may be a *left* child if the level has no node further right.

The tree is given as a level-order array where null marks a missing child: [1, 2, 3, null, 5, null, 4].

Example cases

  • classic
    in root = [1,2,3,null,5,null,4]25134
    out [1,3,4]
    Level 0: 1; level 1: rightmost is 3; level 2: 4.
  • left visible
    in root = [1,2,3,4]4213
    out [1,3,4]
    Level 2 has only the left child 4, so it's the visible one.
  • empty
    in root = []null
    out []

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
Saved
root =
[1,2,3,null,5,null,4]