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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 236: Lowest Common Ancestor of a Binary Tree
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- 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