Last active
December 13, 2015 20:58
-
-
Save sahid/4973851 to your computer and use it in GitHub Desktop.
Find the least common ancestor in a binary tree in Python.
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
| def lca(node, n1, n2): | |
| if match(node.left, n1) and match(node.left, n2): | |
| return lca(node.left, n1, n2) # until we find the least common ancestor by node.left | |
| if match(node.right, n1) and match(node.right, n2): | |
| return lca(node.right, n1, n2) # until we find the least common ancestor by node.right | |
| return node | |
| def match(node, n): | |
| if node is None: return False | |
| if node == n: return True | |
| return match(node.left) or match(node.rigth) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Match function takes two arguments but you are passing only one at line 11.