Skip to content

How to Fix Lowest Common Ancestor in BST Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Lowest Common Ancestor in BST Errors. We cover key concepts, practical examples, and best practices.

Fix lowest common ancestor in bst errors when ancestor search doesn't use BST properties or direction inverted.

Quick Fix

Wrong

def lca(r,p,q):
    if not r: return None
    if r.val>p.val and r.val>q.val: return lca(r.right,p,q)

Wrong direction: both values less -> should go LEFT not right.

def lca(r,p,q):
    cur=r
    while cur:
        if p.val<cur.val and q.val<cur.val: cur=cur.left
        elif p.val>cur.val and q.val>cur.val: cur=cur.right
        else: return cur
    return None
BST [6,2,8,0,4,7,9,null,null,3,5], p=2,q=8 -> 6. O(log n).

Prevention

If both values < root, go left. Both > root, go right. Otherwise root is LCA.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is LCA?

Lowest Common Ancestor: deepest node with both p and q as descendants.

Why split point works?

When p < root and q > root, they're in different subtrees. Root is LCA.

If p or q = root?

Root returns via else branch.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro