VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 10: Trees and BSTs

Lesson 10.8 of 14 in this module Unrolled Pro

Lowest Common Ancestor of a Binary Tree

The deepest node that has both p and q as descendants. From recording the root-to-node path of each and comparing them (two searches plus O(h) paths), to one post-order pass where each subtree reports what it found and the first node to hear from both sides is the answer. Then the binary search tree version that walks down in O(h), many queries answered with parent pointers or binary lifting, nodes that might be missing, and the ML use: the lowest common ancestor of two labels in a class hierarchy, which measures how bad a misclassification is.

about 15 min 5 Python examples 2 quick checks

Problem. Given a binary tree and two nodes p and q in it, return their lowest common ancestor (LCA): the deepest node that has both as descendants. A node counts as a descendant of itself.

text
          3
        /   \
       5     1           LCA(5, 1) = 3
      / \   / \          LCA(5, 4) = 5    (5 is an ancestor of 4, and of itself)
     6   2 0   8         LCA(6, 4) = 5
        / \
       7   4

The new idea: a recursive call can return "what I found" (nothing, p, q, or the answer) rather than a number, and the first node where both sides report something is where p and q's paths meet.

ML context. Labels are often hierarchical: ImageNet classes sit in WordNet, products in a category tree, diagnoses in ICD codes. Confusing a terrier with a beagle (LCA: "dog") is a milder error than confusing it with a truck (LCA: "entity"). The depth of the LCA, or the tree distance through it, measures mistake severity and powers hierarchical metrics and losses (Change D).


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Lowest Common Ancestor of a Binary Tree"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee