Skip to content

Instantly share code, notes, and snippets.

@sahid
Last active December 13, 2015 20:58
Show Gist options
  • Select an option

  • Save sahid/4973851 to your computer and use it in GitHub Desktop.

Select an option

Save sahid/4973851 to your computer and use it in GitHub Desktop.
Find the least common ancestor in a binary tree in Python.
def lca(node, n1, n2):
if match(node.left, n1) and match(node.left, n2):
return lca(node.left, n1, n2) # until we find the least common ancestor by node.left
if match(node.right, n1) and match(node.right, n2):
return lca(node.right, n1, n2) # until we find the least common ancestor by node.right
return node
def match(node, n):
if node is None: return False
if node == n: return True
return match(node.left) or match(node.rigth)
@ravening
Copy link

Match function takes two arguments but you are passing only one at line 11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment