☕ Buy Me Coffee
← Back to Feed

DSA Pattern: Lowest Common Ancestor

Lowest Common Ancestor (LCA) in a tree is the deepest node that has both nodes p and q as descendants.

BST Approach

Leverage BST property: if both p and q are smaller than root, go left. If larger, go right. Otherwise, current root is the LCA.

General Binary Tree

Use DFS. If current node is p or q, return it. Recursively search left and right subtrees. If both subtrees return non-null, current node is the LCA.

// FEEDBACK_LOOP.exe

0.0 / 5.0
FROM 0 PEERS
→ Login to rate