Skip to content

Instantly share code, notes, and snippets.

@vmarois
Created June 6, 2021 09:39
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 vmarois/93a6d9354b6ad02f068784263154f74f to your computer and use it in GitHub Desktop.
Save vmarois/93a6d9354b6ad02f068784263154f74f to your computer and use it in GitHub Desktop.
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
def dfs(root: TreeNode) -> TreeNode:
stack, found, ancestor = [], 0, None
while root or stack:
while root:
stack.append((root, found))
root = root.left
root, had_already_found_one = stack.pop()
found += root in [p,q]
if found == 2:
return ancestor if had_already_found_one else root
elif not had_already_found_one and found == 1:
ancestor = root
root = root.right
return dfs(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment