Last active
January 4, 2017 00:11
-
-
Save liondancer/98ecc92448b856d97f5d4241f3568e00 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, p, q): | |
""" | |
:type root: TreeNode | |
:type p: TreeNode | |
:type q: TreeNode | |
:rtype: TreeNode | |
""" | |
if max(p.val, q.val) < root.val: | |
return lowestCommonAncestor(root.left, p, q) | |
elif min(p.val, q.val) > root.val: | |
return lowestCommonAncestor(root.right, p, q) | |
else: | |
return root | |
def lowestCommonAncestorIterative(root, p, q): | |
while root: | |
if max(p.val, q.val) < root.val: | |
root = root.left | |
elif min(p.val, q.val) > root.val: | |
root = root.right | |
else: | |
return root |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment