Skip to main content

235. Lowest Common Ancestor of a Binary Search Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

Python

First Solution

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

if root.val == p.val or root.val == q.val:
# Hit the target, current root is p or q
return root

if p.val > root.val and q.val > root.val:
# Find targets from the right tree
return self.lowestCommonAncestor(root.right, p, q)
elif p.val < root.val and q.val < root.val:
# Find targets from the left tree
return self.lowestCommonAncestor(root.left, p, q)

# Both left and right are reaching the targets, current node is the answer
return root

Second Solution

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
targets = (p.val, q.val)

def find(node):
if not node:
return

if node.val in targets:
return node

if all(node.val > t for t in targets):
return find(node.left)

if all(node.val < t for t in targets):
return find(node.right)

return node


return find(root)