Created
February 7, 2022 07:09
-
-
Save amarjitdhillon/0260175c9346e7cbe292b4cbafb566cb to your computer and use it in GitHub Desktop.
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
class Solution: | |
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': | |
# In base case, the `not root` is the null case, other cases means we have found the node we are looking for | |
if not root or root == p or root == q: | |
return root | |
x = self.lowestCommonAncestor(root.left, p, q) | |
y = self.lowestCommonAncestor(root.right, p, q) | |
if (x and y) or root in [p,q]: # root in [p,q] as node can be ancestor of itself | |
return root | |
else: | |
return x or y # if either of one is found then return that node |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment