Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created November 24, 2020 12:51
Show Gist options
  • Select an option

  • Save codecakes/6fb22e3b0e1b95c40dfef029902bb9ff to your computer and use it in GitHub Desktop.

Select an option

Save codecakes/6fb22e3b0e1b95c40dfef029902bb9ff to your computer and use it in GitHub Desktop.
Binary Search Tree : Lowest Common Ancestor
from typing import Union
def lca(root: Node, v1: int, v2: int) -> Union[None, Node]:
if not root: return None
res = None
if root.info == v1 or root.info == v2:
res = root
left_res = lca(root.left, v1, v2)
if left_res and res: return res
right_res = lca(root.right, v1, v2)
if right_res and res: return res
if left_res and right_res:
return root
return left_res or right_res or res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment