Created
January 3, 2017 19:55
-
-
Save liondancer/89fce8cbf33780cd3504592ea1597dba to your computer and use it in GitHub Desktop.
Lowest Common Ancestor of a Binary 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
def lowestCommonAncestor(self, root, p, q): | |
# O(n) runtime and constant space | |
if root in (None, p, q): return root | |
left = lowestCommonAncestor(root.left, p, q) | |
right = lowestCommonAncestor(root.right, p, q) | |
if left and right: | |
return root | |
if left: | |
return left | |
return right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment