Skip to content

Instantly share code, notes, and snippets.

@iamprayush
Created September 18, 2020 10:14
Show Gist options
  • Save iamprayush/ef56a0a922be6474a0a3f2554cd1028c to your computer and use it in GitHub Desktop.
Save iamprayush/ef56a0a922be6474a0a3f2554cd1028c to your computer and use it in GitHub Desktop.
Lowest Common Ancestor of a Binary Search Tree
class Solution:
def lowestCommonAncestor(self, node, p, q):
if not node:
return None
if p.val < node.val < q.val or p.val > node.val > q.val or node.val in (p.val, q.val):
return node
if p.val < node.val and q.val < node.val:
# Both nodes are on current node's left.
return self.lowestCommonAncestor(node.left, p, q)
# Otherwise both nodes are on current node's right.
return self.lowestCommonAncestor(node.right, p, q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment