Last active
October 9, 2015 16:44
-
-
Save dusan87/cdf776a6fdbd893c914e 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 Node(object): | |
def __init__(self, value, parentNode): | |
self.value = value | |
self.parent = parentNode | |
# match node that has particular value | |
def match_node(ancs, matcher): | |
for node in ancs: | |
if matcher(node): | |
return node | |
# find all ancesors for node | |
def node_ancesors(node): | |
ancesors = [node, ] | |
while node.parent: | |
node = node.parent | |
ancesors.append(node) | |
return ancesors | |
def lca(node1, node2): | |
ancs1 = node_ancesors(node1) | |
ancs2 = node_ancesors(node2) | |
# list out ancesors values for node1, node2 | |
# do intersection; get max value, which value of closest ancesor | |
closest = max(set([node.value for node in ancs1]) & set([node.value for node in ancs1])) | |
# match node that has closest value | |
node = match_node(ancs1, lambda n: n.value == closest) | |
print node.value | |
def improved_lca(node1, node2): | |
""" | |
Add some conditions that could accelerate preforming in some particular cases | |
""" | |
if node1.value == node2.value: # same node | |
return node1 | |
if not node1.parent: # node1 is root | |
return node1 | |
if not node2.parent: # node2 is root | |
return node2 | |
if node1.parent.value == node2.parent.value: # have same ancesor | |
return node1.parent | |
return lca(node1, node2) # call the same logic if no | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment