00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each recursive call returns p, q, the LCA, or null. A node that receives non-null results from both sides is the LCA; otherwise it passes up whichever side found something.

Approaches

The recursive approach finds the answer in one traversal. The parent-map approach records ancestors explicitly.

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 and h the height. Both approaches may visit every node; the parent map stores one entry per node.

Interview Tips and Recommended Approach

  • Handle the ancestor case. Returning a node as soon as it equals p or q covers it.
  • Use the BST shortcut when possible. In a BST, compare values and go left or right only.
  • Ask whether p and q are guaranteed to exist; if not, verify both were found.
  • Know the uses: distances between nodes and organisation-chart queries.

Recommended Approach: Single Recursive Pass

Why: it finds the answer in a single traversal with no extra data structures, using a short and elegant recursion.