Skip to content

Instantly share code, notes, and snippets.

@liondancer
Last active January 4, 2017 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liondancer/98ecc92448b856d97f5d4241f3568e00 to your computer and use it in GitHub Desktop.
Save liondancer/98ecc92448b856d97f5d4241f3568e00 to your computer and use it in GitHub Desktop.
def lowestCommonAncestor(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if max(p.val, q.val) < root.val:
return lowestCommonAncestor(root.left, p, q)
elif min(p.val, q.val) > root.val:
return lowestCommonAncestor(root.right, p, q)
else:
return root
def lowestCommonAncestorIterative(root, p, q):
while root:
if max(p.val, q.val) < root.val:
root = root.left
elif min(p.val, q.val) > root.val:
root = root.right
else:
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment