Created
September 18, 2020 10:14
-
-
Save iamprayush/ef56a0a922be6474a0a3f2554cd1028c to your computer and use it in GitHub Desktop.
Lowest Common Ancestor of a Binary Search Tree
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
class Solution: | |
def lowestCommonAncestor(self, node, p, q): | |
if not node: | |
return None | |
if p.val < node.val < q.val or p.val > node.val > q.val or node.val in (p.val, q.val): | |
return node | |
if p.val < node.val and q.val < node.val: | |
# Both nodes are on current node's left. | |
return self.lowestCommonAncestor(node.left, p, q) | |
# Otherwise both nodes are on current node's right. | |
return self.lowestCommonAncestor(node.right, p, q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment