loading

Binary Tree Right Side View — Step-by-Step Visualization

mediumLeetCode #199TreeDFSBFSBinary Tree

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Algorithm Pattern

Level-Order Traversal (BFS)

Key Idea

To get the 'right side' view, we can perform a BFS (Level Order Traversal). At each level, the last node we visit is the one visible from the right side. Alternatively, handle DFS with the right child first and keep track of the depth already visited.

Step-by-Step Approach

  1. Initialize `res = []` and `queue = [root]`.
  2. While queue is not empty:
  3. Get the current level size `n`.
  4. Iterate `n` times to process all nodes in the current level.
  5. For each node, add its children to the queue.
  6. The last node in this loop is added to `res`.
  7. Return `res`.

Common Gotchas

  • Make sure to handle empty trees.
  • The BFS approach is more intuitive for 'level-by-level' visibility.

Related Problems