AlgoTales · Roadmap

Lowest common ancestor

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The lowest common ancestor of two nodes is the deepest node that sits above both of them. It is the closest shared parent, such as the nearest folder that contains two files or the point where two git branches split.

Practical use cases

  • Web app: Shared parent folder for two files. A file manager has a "Move both files together" feature. It must find the closest folder that contains both chosen files. Walking up from each file until the paths meet gives that folder, and the app can then offer it as the destination.
  • Web app: Highlighting a shared card. A JavaScript page needs to know the nearest element that contains two clicked items, for example to highlight the shared card. Finding their lowest common ancestor in the page tree gives that element straight away, without looping over every parent of both items.
  • System: Git merge base. When you merge a branch, git looks for the latest commit that both branches share, called the merge base. That is the lowest common ancestor in the commit history, and it lets git combine only the changes made on each branch since then.

The story: Where Do the Cousins Meet?

At Grandpa Bhaskar's birthday, two distant cousins, Aarav and Zoya, met for the first time and wondered: "How are we related?" The family chart on the wall showed Grandpa at the top, his children below him, and their children below them.

Mira said: "Follow each of your lines upward until they join. The first person where both lines meet is your closest shared ancestor." Aarav went up: his mother, then his grandmother. Zoya went up: her father, then her grandmother too. They met at the same grandmother, not at Grandpa himself.

That meeting point is the lowest common ancestor, or LCA: the lowest person on the chart who has both cousins somewhere below them. If you ask about a grandmother and her own granddaughter, the answer is the grandmother herself, since a person counts as her own ancestor.

A computer has no wall chart to trace by finger. So Mira taught it a shout-and-listen trick: every person asks their two sides, "did you find Aarav or Zoya?" The first person who hears "yes" from both sides is the LCA.

How to spot this problem, and where you need it

You have two items in a hierarchy and need their closest shared parent, to find where they meet, what they have in common, or where two lines of history split.

Signs you need it

  • The problem says "lowest common ancestor", "closest shared parent", "where do the paths meet" or "merge base".
  • You are walking both items up to the root by hand and comparing lists of parents.
  • You need the nearest common category, folder, manager or commit for two selected items.

Where to use it in a project

  • Org-chart or category features that find the nearest shared manager or shared category of two items.
  • Version control and DOM tools that look for the point where two paths diverge.

The solution

Start at the root and ask both sides of each node whether they contain either target. If the current node is one of the targets, return it. Look in the left child and in the right child. If both sides return something, the current node is the first meeting point, so it is the answer. If only one side returns something, pass that up. One walk is enough.

Payoff: Before: listing every ancestor of both nodes and comparing. After: one pass down the tree that finds the meeting point directly.

Explain it like I am 8

Two kids are standing somewhere on a big family chart. Each walks upwards towards Grandpa. The first spot where their two walks join together is the lowest common ancestor: their closest shared grandparent.

How it works, step by step

  1. Start at the root and look for the two target nodes p and q.
  2. If the current node is empty, or is p or q itself, return it ("found one here, or nothing").
  3. Ask the left side and the right side the same question (recursion).
  4. If both sides returned something, then p and q are on different sides, so this node is the LCA: return it.
  5. If only one side returned something, pass that answer up unchanged. That answer is either one target or the already-found LCA.

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Returns the LCA of nodes with values $p and $q.
function lca(?TreeNode $n, int $p, int $q): ?TreeNode {
    if ($n === null || $n->val === $p || $n->val === $q) return $n;   // found one, or fell off
    $left  = lca($n->left, $p, $q);
    $right = lca($n->right, $p, $q);
    if ($left !== null && $right !== null) return $n;   // answers from BOTH sides: meeting point
    return $left ?? $right;                              // pass along whichever answered
}

$root = sampleTree();
foreach ([[7, 4], [7, 6], [2, 7], [4, 5]] as [$a, $b]) {
    echo "LCA($a, $b) = " . lca($root, $a, $b)->val . PHP_EOL;
}
// LCA(7, 4) = 2   LCA(7, 6) = 1   LCA(2, 7) = 2   LCA(4, 5) = 2

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Returns the LCA of nodes with values p and q.
function lca(n, p, q) {
  if (n === null || n.val === p || n.val === q) return n;   // found one, or fell off
  const left = lca(n.left, p, q);
  const right = lca(n.right, p, q);
  if (left !== null && right !== null) return n;   // answers from BOTH sides: meeting point
  return left !== null ? left : right;             // pass along whichever answered
}

const root = sampleTree();
for (const [a, b] of [[7, 4], [7, 6], [2, 7], [4, 5]]) {
  console.log('LCA(' + a + ', ' + b + ') = ' + lca(root, a, b).val);
}
// LCA(7, 4) = 2   LCA(7, 6) = 1   LCA(2, 7) = 2   LCA(4, 5) = 2

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Returns the LCA of nodes with values p and q.
    static TreeNode lca(TreeNode n, int p, int q) {
        if (n == null || n.val == p || n.val == q) return n;   // found one, or fell off
        TreeNode left = lca(n.left, p, q);
        TreeNode right = lca(n.right, p, q);
        if (left != null && right != null) return n;           // answers from BOTH sides: meeting point
        return left != null ? left : right;                    // pass along whichever answered
    }

    public static void main(String[] args) {
        TreeNode root = sampleTree();
        int[][] pairs = {{7, 4}, {7, 6}, {2, 7}, {4, 5}};
        for (int[] pair : pairs) {
            System.out.println("LCA(" + pair[0] + ", " + pair[1] + ") = " + lca(root, pair[0], pair[1]).val);
        }
        // LCA(7, 4) = 2   LCA(7, 6) = 1   LCA(2, 7) = 2   LCA(4, 5) = 2
    }
}

Go

package main

import (
	"fmt"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// lca returns the lowest common ancestor of the nodes with values p and q.
func lca(n *TreeNode, p, q int) *TreeNode {
	if n == nil || n.Val == p || n.Val == q {
		return n // found one, or fell off
	}
	left := lca(n.Left, p, q)
	right := lca(n.Right, p, q)
	if left != nil && right != nil {
		return n // answers from BOTH sides: meeting point
	}
	if left != nil { // pass along whichever answered
		return left
	}
	return right
}

func main() {
	root := sampleTree()
	for _, pair := range [][2]int{{7, 4}, {7, 6}, {2, 7}, {4, 5}} {
		fmt.Printf("LCA(%d, %d) = %d\n", pair[0], pair[1], lca(root, pair[0], pair[1]).Val)
	}
	// LCA(7, 4) = 2   LCA(7, 6) = 1   LCA(2, 7) = 2   LCA(4, 5) = 2
}

Time: O(n) · Extra space: O(h). In the worst case every node is visited once; the call stack is as deep as the tree is tall.

Watch out for

  • Forgetting that a node can be its own ancestor. LCA(2, 7) is 2, not 1.
  • Using this version when one of the values might be missing from the tree: it can return a wrong node. Confirm both exist first.
  • Looking only at the nodes' depths instead of recursing; the answer depends on where the paths meet, not on how deep each node is.

Quick check

  1. In the example tree, what is the LCA of 7 and 6?
    • 2
    • 3
    • 1
    • 5
  2. A node gets an answer from both its left and right sides. What does it do?
    • Returns the left answer
    • Searches again
    • Returns itself: it is the LCA
  3. What is the LCA of a node and its own descendant?
    • The node&#39;s parent
    • The node itself
    • The root