Problem 235

Abstract / Summary

Find the first node where the values of both given nodes are on its left and right subtrees or it matches one of the nodes.

Note

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

Python 0235.py

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

        if root.val in [ p.val, q.val ]:
            return root

        left  = min(p.val, q.val)
        right = max(p.val, q.val)
        if right < root.val:
            return self.lowestCommonAncestor(root.left,  p, q)
        if left  > root.val:
            return self.lowestCommonAncestor(root.right, p, q)

        return root
16 lines | 515 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Binary Search Tree
  • 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 method lowestCommonAncestor that finds the lowest common ancestor (LCA) of two nodes p and q in a binary search tree (BST). The algorithm leverages the ordering property of BSTs: for any node, all values in the left subtree are smaller and all values in the right subtree are larger. By comparing the values of p, q, and the current root, the method recursively descends toward the region where the two target nodes diverge, which is precisely the LCA.

Key Steps

The method begins with a guard clause that returns None when the input root is empty, handling the trivial case of an empty tree.

if not root:
    return None

Next, it checks whether the current root matches either of the target nodes. If the value of root equals p.val or q.val, the current node is returned as the LCA because a node is considered an ancestor of itself.

if root.val in [ p.val, q.val ]:
    return root

The algorithm then determines the relative ordering of p and q by computing the minimum and maximum of their values. These variables, left and right, represent the lower and higher bounds of the search interval.

left  = min(p.val, q.val)
right = max(p.val, q.val)

A comparison between right and root.val decides whether both target nodes lie entirely in the left subtree. If right is less than root.val, the recursion proceeds leftward.

if right < root.val:
    return self.lowestCommonAncestor(root.left,  p, q)

Conversely, a comparison between left and root.val determines if both nodes reside in the right subtree. If left exceeds root.val, the recursion proceeds rightward.

if left  > root.val:
    return self.lowestCommonAncestor(root.right, p, q)

When neither of the above conditions holds, the current root sits between left and right, meaning p and q are split across different subtrees (or one equals root). In this situation, root is the lowest common ancestor and is returned.

return root

Edge Cases Handled

The implementation explicitly handles the scenario where the tree is empty by returning None immediately. It also correctly treats the case where one of the target nodes is the ancestor of the other; the early equality check (root.val in [ p.val, q.val ]) ensures that the ancestor node is returned without further recursion. Additionally, the use of min and max guarantees correct behavior regardless of the order in which p and q are supplied, so the method works whether p.val is smaller or larger than q.val.

Performance Optimizations

The algorithm benefits from early termination through the equality check, which avoids unnecessary traversal when the current node matches one of the targets. By computing left and right once per call, the code eliminates redundant comparisons in the subsequent conditional branches. The recursive descent follows a single path down the tree, never exploring both subtrees simultaneously, which keeps the number of visited nodes proportional to the depth of the tree. This depth-first approach exploits the BST property to prune large portions of the search space, resulting in an efficient traversal that stops as soon as the LCA is identified.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree that spreads out like branches on a giant tree. Each spot in this tree holds a special number. You are looking for two specific friends, who are hiding in different parts of this tree, and you want to find the very first place where their paths meet.

The computer starts at the very top of the tree, which is called the root. If the spot is empty, there is nobody there to find. If the computer happens to land on one of the friends right away, then that spot is where they are standing.

Next, the computer looks at the numbers and compares them to the spot where it is currently standing. If both friends have smaller numbers than the current spot, the computer knows they must be hiding somewhere down the left branch, so it moves over there to keep looking. If both friends have bigger numbers than the current spot, they must be hiding somewhere down the right branch, so the computer moves over there instead.

If the friends are not both smaller and not both bigger, it means the computer has found the special spot where their paths come together. This is the place where the two branches meet to lead to both friends.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.93

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 C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fsq C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
qiyuangong Python
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fsq C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
qiyuangong Python
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
50 links | 35 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Trees (Python)'
Greg Hogg 9 mins
Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Trees (Python)
YouTube video 'Lowest Common Ancestor of a Binary Search Tree - LeetCode  235 - Python'
Deepti Talesra 11 mins
Lowest Common Ancestor of a Binary Search Tree - LeetCode 235 - Python
YouTube video '[Java] Leetcode 235. Lowest Common Ancestor of a Binary Search Tree [Binary Search Tree #4]'
Eric Programming 5 mins
[Java] Leetcode 235. Lowest Common Ancestor of a Binary Search Tree [Binary Search Tree #4]
YouTube video 'Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | C++ | Python | Hindi'
Ayushi Sharma 8 mins
Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | C++ | Python | Hindi
YouTube video 'LeetCode 235. Lowest Common Ancestor of a Binary Search Tree - Interview Prep Ep 137'
Fisher Coder 11 mins
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree - Interview Prep Ep 137
YouTube video 'Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | Live coding session'
Coding Decoded 6 mins
Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | Live coding session
YouTube video '235. Lowest Common Ancestor of a Binary Search Tree | JavaScript | Recursion | LeetCode 75 | Easy'
LeetCodeWithMonu 6 mins
235. Lowest Common Ancestor of a Binary Search Tree | JavaScript | Recursion | LeetCode 75 | Easy
YouTube video 'Lowest Common Ancestor of a Binary Search Tree - 235. LeetCode - Java'
Teddy Smith 8 mins
Lowest Common Ancestor of a Binary Search Tree - 235. LeetCode - Java
YouTube video 'Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | bst | Recursive Iterative'
Naresh Gupta 9 mins
Lowest Common Ancestor of a Binary Search Tree | Leetcode 235 | bst | Recursive Iterative
YouTube video 'Daily Leetcode #864: Aug 12, 2022 - 235. Lowest Common Ancestor of a Binary Search Tree'
Programming Live with Larry 5 mins
Daily Leetcode #864: Aug 12, 2022 - 235. Lowest Common Ancestor of a Binary Search Tree
YouTube video 'Daily Leetcode #475: Jul 19, 2021 - 235. Lowest Common Ancestor of a Binary Search Tree'
Programming Live with Larry 10 mins
Daily Leetcode #475: Jul 19, 2021 - 235. Lowest Common Ancestor of a Binary Search Tree
YouTube video 'LeetCode:235 - Lowest Common Ancestor of Binary Search Tree in Swift'
Data Structures and Algorithm in Swift 8 mins
LeetCode:235 - Lowest Common Ancestor of Binary Search Tree in Swift
YouTube video '235. Lowest Common Ancestor of a Binary Search Tree | Leetcode | Binary Search Tree | DSA'
Coding with Tamilarasan 8 mins
235. Lowest Common Ancestor of a Binary Search Tree | Leetcode | Binary Search Tree | DSA
YouTube video 'Leetcode 235: Lowest Common Ancestor of a Binary Search Tree'
Algorithms Casts 4 mins
Leetcode 235: Lowest Common Ancestor of a Binary Search Tree
YouTube video '51. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : Javascript'
Web Fusion with Bharadwaj 18 mins
51. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : Javascript
YouTube video 'Day 238: LeetCode Problem 235. Lowest Common Ancestor of a Binary Search Tree - Swift'
iOSxBank 11 mins
Day 238: LeetCode Problem 235. Lowest Common Ancestor of a Binary Search Tree - Swift
YouTube video '96. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : JAVA'
Web Fusion with Bharadwaj 13 mins
96. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : JAVA
YouTube video '28. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : JAVA'
Web Fusion with Bharadwaj 14 mins
28. Leetcode 235. Lowest Common Ancestor of a Binary Search Tree : JAVA
YouTube video 'Lowest Common Ancestor of a Binary Search Tree - LeetCode #235 - C++'
Sean Chuah 6 mins
Lowest Common Ancestor of a Binary Search Tree - LeetCode #235 - C++
YouTube video 'Leetcode 235. Lowest Common Ancestor of a Binary Search Tree [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 8 mins
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree [ JAVASCRIPT ].
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 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