Skip to content

Instantly share code, notes, and snippets.

@sakhayadeep
Last active November 9, 2019 06:34
Show Gist options
  • Save sakhayadeep/f9ce1f63e294f0376cd0737c2f37d7d4 to your computer and use it in GitHub Desktop.
Save sakhayadeep/f9ce1f63e294f0376cd0737c2f37d7d4 to your computer and use it in GitHub Desktop.
Lowest common ancestor in a tree
class Node:
def __init__(self, val, parent = None):
self.val = val
self.parent = parent
self.left = None
self.right = None
class Tree:
def __init__(self, val_list):
self.root = Node(val_list.pop(0))
q = [self.root]
while val_list:
temp = q.pop(0)
temp.left = Node(val_list.pop(0), temp)
q.append(temp.left)
if val_list:
temp.right = Node(val_list.pop(0), temp)
q.append(temp.right)
def findNode(self, a):
if self.root.val == a:
return self.root
queue = [self.root]
while queue:
temp = queue.pop(0)
if temp.val == a:
return temp
if temp.left != None:
queue.append(temp.left)
if temp.right != None:
queue.append(temp.right)
return None
def findLCA(self, a, b):
a = self.findNode(a)
b = self.findNode(b)
if a == None or b == None or a == self.root or b == self.root:
return Node(None)
ancestor_a = set()
ancestor_b = set()
while ancestor_a.intersection(ancestor_b) == set():
try:
ancestor_a.add(a.parent)
a = a.parent
except:
pass
try:
ancestor_b.add(b.parent)
b = b.parent
except:
pass
res = list(ancestor_a.intersection(ancestor_b))
if res:
return res[0]
return Node(None)
#driver code
#a = list(map(int, input().split()))
a = [5, 7, 3, 6, 8, 2, 9, 10]
tree = Tree(a)
print(tree.findLCA(3, 10).val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment