Problem 236

Abstract / Summary

Given a binary tree and two nodes find their lowest common ancestor node.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0236.py

class Solution:
    tracks = { }
    nodes  = { }
    relevant = []

    def getPath(self, root, track):
        if not root:
            return None

        next = track + [ root.val ]
        if root.val in self.relevant:
            self.tracks[root.val] = next
        self.nodes[root.val] = root

        self.getPath(root.left,  next)
        self.getPath(root.right, next)


    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or not p or not q:
            return None

        self.relevant = [ p.val, q.val ]

        self.getPath(root, [])

        one = self.tracks[p.val].copy()
        two = self.tracks[q.val].copy()

        result = root
        while len(one) > 0 and len(two) > 0:
            if one[0] != two[0]:
                break

            result = self.nodes[one[0]]
            del one[0]
            del two[0]

        return result
39 lines | 971 bytes | submitted August 22, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (3+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class that computes the lowest common ancestor (LCA) of two nodes in a binary tree. It builds complete root-to-node paths for the two target values, stores each node in a dictionary for constant-time access, and then walks the two paths in parallel until the first divergence is found. The node at the last matching position is returned as the LCA.

Key Steps

The algorithm is organized around two methods: getPath and lowestCommonAncestor.

The getPath routine performs a depth-first traversal, constructing a path list as it descends. For each visited node it updates two class-level dictionaries: tracks records the full path for any node whose value appears in the relevant list, and nodes maps a node value to the actual TreeNode instance. The recursion continues for both left and right children, passing a copy of the current path.

def getPath(self, root, track):
    if not root:
        return None

    next = track + [ root.val ]
    if root.val in self.relevant:
        self.tracks[root.val] = next
    self.nodes[root.val] = root

    self.getPath(root.left,  next)
    self.getPath(root.right, next)

The lowestCommonAncestor method first guards against null inputs, then populates the relevant list with the values of the two query nodes. It invokes getPath to fill the dictionaries, extracts copies of the two stored paths, and iterates while the leading elements of both paths are identical. During each iteration it updates result to the node corresponding to the shared value and removes the processed element from both path lists. When a mismatch occurs the loop stops and the most recent common node is returned.

def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
    if not root or not p or not q:
        return None

    self.relevant = [ p.val, q.val ]

    self.getPath(root, [])

    one = self.tracks[p.val].copy()
    two = self.tracks[q.val].copy()

    result = root
    while len(one) > 0 and len(two) > 0:
        if one[0] != two[0]:
            break

        result = self.nodes[one[0]]
        del one[0]
        del two[0]

    return result

Edge Cases Handled

The code explicitly checks for a missing root or missing query nodes at the start of lowestCommonAncestor. If any of these are None, the method returns None immediately, preventing further processing on invalid inputs. During the depth-first traversal, the base case if not root: return None ensures that leaf children are handled without error. The path construction logic only records a path when the current node’s value matches one of the two target values, which means the algorithm gracefully deals with trees where the targets are located at different depths or where one target is the root itself. The parallel walk through the two path lists stops as soon as a mismatch is detected, correctly handling the situation where the two nodes share only the root as a common ancestor.

Performance Optimizations

The implementation leverages two dictionaries to achieve constant-time lookups. nodes maps each encountered value to its corresponding TreeNode, allowing the algorithm to retrieve the actual node object directly from a value without additional traversal. tracks stores the complete root-to-target path for each relevant node, eliminating the need to recompute paths during the comparison phase. By copying the stored paths once and then mutating the copies with del, the algorithm avoids repeated slicing or index calculations while walking the paths. The early break in the while loop prevents unnecessary iteration once the divergence point is reached, ensuring that only the shared prefix of the two paths is examined. This combination of dictionary lookups and minimal path processing yields an efficient solution for the LCA problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree made of branches that reach down like an upside-down plant. This code is like a little explorer walking through every single branch to find where two specific people live. First, the explorer starts at the very top of the tree and walks down every path. While walking, the explorer writes down a map of how to get from the top to each person. If the explorer finds someone the family is looking for, a special note is saved to remember that exact path.

Once the explorer has maps for both people, the job is to see where their paths are the same. The explorer looks at the start of both maps. Since they both begin at the very top, the paths match at first. The explorer keeps moving forward as long as the paths are identical. When the paths finally go in different directions, the explorer stops at the last place where they were together. That last spot is the common ancestor where both paths split apart. It is like finding the highest point where two siblings meet before heading to their own separate rooms.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.65 | σ = 1.69

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C++
linouk23 C++
lkwq007 Python
MacJim C++
qiyuangong Java
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C++
linouk23 C++
lkwq007 Python
MacJim C++
qiyuangong Java
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
54 links | 38 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LOWEST COMMON ANCESTOR OF A BINARY TREE I | PYTHON | LEETCODE 236'
Cracking FAANG 13 mins
LOWEST COMMON ANCESTOR OF A BINARY TREE I | PYTHON | LEETCODE 236
YouTube video 'Lowest Common Ancestor of a Binary Tree | Leetcode 236 | Microsoft | Amazon | codestorywithMIK'
codestorywithMIK 17 mins
Lowest Common Ancestor of a Binary Tree | Leetcode 236 | Microsoft | Amazon | codestorywithMIK
YouTube video 'Lowest Common Ancestor of a binary tree | Leetcode #236'
Techdose 18 mins
Lowest Common Ancestor of a binary tree | Leetcode #236
YouTube video 'Lowest Common Ancestor of a Binary Tree | Leetcode #236 | Trees - 7'
Algorithms Made Easy 9 mins
Lowest Common Ancestor of a Binary Tree | Leetcode #236 | Trees - 7
YouTube video '[Java] Leetcode 236. Lowest Common Ancestor of a Binary Tree [Binary Tree #8]'
Eric Programming 7 mins
[Java] Leetcode 236. Lowest Common Ancestor of a Binary Tree [Binary Tree #8]
YouTube video 'LEETCODE 236 (JAVASCRIPT) | LOWEST COMMON ANCESTOR OF A BINARY TREE'
Andy Gala 13 mins
LEETCODE 236 (JAVASCRIPT) | LOWEST COMMON ANCESTOR OF A BINARY TREE
YouTube video 'LeetCode 236: Lowest Common Ancestor of a Binary Tree'
Engineering Digest 11 mins
LeetCode 236: Lowest Common Ancestor of a Binary Tree
YouTube video 'Lowest Common Ancestor of a Binary Search Tree - LeetCode 236 - Coding Interview'
One Code Man 4 mins
Lowest Common Ancestor of a Binary Search Tree - LeetCode 236 - Coding Interview
YouTube video 'Lowest Common Ancestor of a Binary Tree - LeetCode 236 - JavaScript'
AlgoJS 6 mins
Lowest Common Ancestor of a Binary Tree - LeetCode 236 - JavaScript
YouTube video 'Lowest Common Ancestor of a Binary Tree | Leetcode 236 | Live coding session 🌳🌳🌳'
Coding Decoded 12 mins
Lowest Common Ancestor of a Binary Tree | Leetcode 236 | Live coding session 🌳🌳🌳
YouTube video 'δΊŒε‰ζ ‘ηš„ζœ€ε°ε…¬ε…±η₯–ε…ˆ Lowest Common Ancestor of a Binary Tree'
happygirlzt 10 mins
δΊŒε‰ζ ‘ηš„ζœ€ε°ε…¬ε…±η₯–ε…ˆ Lowest Common Ancestor of a Binary Tree
YouTube video 'Daily Leetcode #847: Jul 26, 2022 - 236. Lowest Common Ancestor of a Binary Tree'
Programming Live with Larry 12 mins
Daily Leetcode #847: Jul 26, 2022 - 236. Lowest Common Ancestor of a Binary Tree
YouTube video 'Lowest Common Ancestor of a Binary Tree'
happygirlzt 9 mins
Lowest Common Ancestor of a Binary Tree
YouTube video 'LCA Variation 1|| 236. Lowest Common Ancestor of a Binary Tree || Leetcode Medium || Tree ||  Cpp'
Komal Pal 27 mins
LCA Variation 1|| 236. Lowest Common Ancestor of a Binary Tree || Leetcode Medium || Tree || Cpp
YouTube video 'Facebook Coding Interview Question | Leetcode 236 | Lowest Common Ancestor of a Binary Tree'
WorkWithGoogler 13 mins
Facebook Coding Interview Question | Leetcode 236 | Lowest Common Ancestor of a Binary Tree
YouTube video '236 Lowest Common Ancestor of a Binary Tree | Leetcode | Binary Tree | DSA'
Coding with Tamilarasan 13 mins
236 Lowest Common Ancestor of a Binary Tree | Leetcode | Binary Tree | DSA
YouTube video 'Leetcode 236 [FB/Meta]. Lowest Common Ancestor of a Binary Tree - Intuition and analogy, 2-solutions'
Code-Yao 15 mins
Leetcode 236 [FB/Meta]. Lowest Common Ancestor of a Binary Tree - Intuition and analogy, 2-solutions
YouTube video 'LeetCode 236. Lowest Common Ancestor of a Binary Tree'
Kacy Codes 4 mins
LeetCode 236. Lowest Common Ancestor of a Binary Tree
YouTube video 'Daily Leetcode #456: Jun 30, 2021 - 236. Lowest Common Ancestor of a Binary Tree'
Programming Live with Larry 14 mins
Daily Leetcode #456: Jun 30, 2021 - 236. Lowest Common Ancestor of a Binary Tree
YouTube video 'Lowest Common Ancestor of a Binary Tree | LeetCode 236 | Coders Camp'
Coders Camp 10 mins
Lowest Common Ancestor of a Binary Tree | LeetCode 236 | Coders Camp
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

3 easy 5 medium
9 solutions   August 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality