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
Difficulty
and has an acceptance rate of about 70% (3+ million submissions).
Typical patterns to solve this problem:
- 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 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.
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.
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 | 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++ |
Videos
Similar Problems
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 1257: Smallest Common Region
- problem 1644: Lowest Common Ancestor of a Binary Tree II
- problem 1650: Lowest Common Ancestor of a Binary Tree III
- problem 2225: Find Players With Zero or One Losses
Solved On The Same Day
- problem 257: Binary Tree Paths
- problem 551: Student Attendance Record I
- problem 605: Can Place Flowers
- problem 289: Game of Life
- problem 397: Integer Replacement
- problem 413: Arithmetic Slices
- problem 525: Contiguous Array
- problem 567: Permutation in String
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