00:00

Problem Statement

Input/Output Examples

Visual Explanation

The deepest level contains only 4 and 7, both in the left subtree, so 7 is visible even though it is not on the right branch.

Approaches

Both approaches pick one node per depth. BFS takes the last of each level; DFS visits the right side first.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of nodes. Both approaches visit every node once; BFS stores one level at a time, DFS one root-to-leaf path.

Interview Tips and Recommended Approach

  • Do not follow only right pointers. Deeper left nodes can be visible, as 7 is here.
  • Read the level size first. The queue grows while the level is being processed.
  • Know the variants: left view, top view and bottom view use similar ideas.
  • Choose by shape. BFS suits wide, shallow trees; DFS suits narrow, deep ones.

Recommended Approach: Level-Order BFS

Why: it maps the definition, "one node per level", directly onto a level-order traversal.