loading

Lowest Common Ancestor of a Binary Tree — Step-by-Step Visualization

mediumLeetCode #236TreeDFSBinary Tree

Given binary tree and two nodes p, q, return their LCA.

Algorithm Pattern

Post-Order DFS

Key Idea

Return the node if it is p or q. LCA is where results from left and right are both non-null.

Step-by-Step Approach

  1. Base case: null or node is p/q → return node
  2. Recurse left and right
  3. If both non-null → this node is LCA
  4. Else return whichever is non-null

Related Problems