Created
November 24, 2020 12:51
-
-
Save codecakes/6fb22e3b0e1b95c40dfef029902bb9ff to your computer and use it in GitHub Desktop.
Binary Search Tree : Lowest Common Ancestor
This file contains hidden or 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
| 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