Skip to content

Instantly share code, notes, and snippets.

@nma
Created March 15, 2020 19:59
Show Gist options
  • Save nma/80394fa4a7f0d11664bdb0e709c0b025 to your computer and use it in GitHub Desktop.
Save nma/80394fa4a7f0d11664bdb0e709c0b025 to your computer and use it in GitHub Desktop.
LCA algorithm with a parent pointer and a set to save time
def find_lca(n1: BinaryTreeNode, n2: BinaryTreeNode) -> Optional[BinaryTreeNode]:
seen_on_path: Set[BinaryTreeNode] = set()
while n1 or n2:
# go up the tree at the same time
if n1:
# at every point check if we have already seen the node
if n1 in seen_on_path:
# first seen will be an ancestor
return n1
seen_on_path.add(n1)
n1 = n1.parent
if n2:
if n2 in seen_on_path:
return n2
seen_on_path.add(n2)
n2 = n2.parent
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment