Graph Theory37 sections · 1633 units
Open in Course

Naive Approach - The Idea

(Climb to same depth)

The simplest approach: store each node's parent, then trace both nodes up to the root. Mark every node you visit on the first path. When the second path hits a marked node, that is your LCA. Here is how it works. Start at node A and walk to the root, marking every ancestor. Then start at node B and walk upward. The first marked node you encounter is the LCA.

Time complexity: O(h)O(h) where hh is tree height. For a balanced tree, this is O(logn)O(\log n). For a skewed tree, this becomes O(n)O(n). Space complexity: O(h)O(h) for the set of marked ancestors. This works fine for one-off queries, but if you need to answer many queries, you will want something faster.