Created
June 6, 2021 09:39
-
-
Save vmarois/93a6d9354b6ad02f068784263154f74f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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