Graph Theory37 sections · 1633 units
Open in Course

Naive Approach - Implementation

(Climbing step by step)

Here is the naive approach implementation:

function naiveLCA(n, parent, u, v):
    marked = set

    // Climb from u to root, marking all ancestors
    current = u
    while current != -1:
        marked.add(current)
        current = parent[current]

    // Climb from v until we hit a marked node
    current = v
    while current != -1:
        if current in marked:
            return current
        current = parent[current]

    return -1

Time: O(h)O(h) where hh is tree height. Space: O(h)O(h) for the set of marked ancestors.