Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Solving All Variations of the Lowest Common Ancestor (LCA) Problem in Binary Trees
Mar 25, 2025
226 views
Written by Prashant Basnet
<section class="bg-white dark:bg-gray-900 px-4 py-8 max-w-2xl mx-auto text-gray-800 dark:text-gray-200">
<h1 class="text-2xl sm:text-3xl font-signature italic font-semibold text-center mb-4">
๐ Welcome โ Youโve Landed on My Signature Page
</h1>
<p class="text-base sm:text-lg mb-4">
Hey, Iโm <strong class="text-black dark:text-white">Prashant Basnet</strong> โ software developmemt engineer at
<a href="https://unisala.com" class="text-indigo-600 dark:text-indigo-400 underline hover:no-underline" target="_blank" rel="noopener noreferrer">
Unisala.com
</a>.
</p>
<p class="text-base sm:text-lg mb-6">
Youโre viewing my <strong>Signature</strong>, a digital space where I share what Iโm learning, building, and reflecting on, all in one place.
</p>
<div class="border-l-4 border-indigo-400 dark:border-indigo-500 pl-4 italic mb-6 text-sm sm:text-base text-gray-700 dark:text-gray-400">
๐ Found this page via LinkedIn, my personal site, or a shared link?
<br />
This isnโt a traditional portfolio. Itโs my public digital notebook where I document useful ideas, experiments, and lessons Iโve learned as I build.
</div>
<h2 class="text-lg font-semibold mb-2">What Youโll Find Here:</h2>
<ul class="list-disc list-inside space-y-1 text-sm sm:text-base">
<li>โ๏ธ Thoughts on algorithms, systems, and software design</li>
<li>๐ง Insights from building at Unisala</li>
<li>๐ Direct links to everything Iโve published on Unisala</li>
</ul>
</section>
Let me walk you through the different variations of the LCA problem and how to solve each one with slight modifications to the core algorithm.
1. Basic LCA Problem
Problem: Find the LCA of two nodes p and q in a binary tree (both nodes guaranteed to exist).
Solution Approach:
2. LCA II - Nodes May Not Exist (Leetcode 1644)
Problem: Find LCA of p and q, but return null if either doesn't exist.
Solution Approach:
// Helper to check if node exists in tree
3. LCA IV - Multiple Nodes (Leetcode 1676)
Problem: Find LCA of an array of nodes (all guaranteed to exist).
Solution Approach:
4. LCA III - With Parent Pointers (Leetcode 1650)
Problem: Find LCA when nodes have parent pointers (no root given).
Solution Approach:
(using hash set):
Key Insights:
The beauty is that all these variations build on the same fundamental concept - finding the deepest node that contains all target nodes in its descendants.