Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created May 10, 2020 16:52
Show Gist options
  • Save jatinsharrma/23dbe76b19049dfc86f57d31c350db92 to your computer and use it in GitHub Desktop.
Save jatinsharrma/23dbe76b19049dfc86f57d31c350db92 to your computer and use it in GitHub Desktop.
Program that returns youngest common ancestor to given two descendants
# //////////////////////////////////////////////////
# ------------Youngest Common Ancestor--------------
# /////////////////////////////////////////////////
'''
Question: You are given a BST and 2 descendants.
Find the yongest common ancestor to the 2 given descendants node.
Example :
4
/ \
2 5
/ \ \
0 3 6
Yongest common ancestor of (0,6) is 4
'''
'''
Logic :
We traverse the BST with respect to both nodes values given to us.
If the new traversed node is same for both that means we haven't reached
the youngest ancestor. If the traversed node is different
we return previously traversed node because it is the youngest ancestor.
Example :
4
/ \
2 5
/ \ \
0 3 6
We have to find youngest ancestor to nodes 0 and 3
We see to the root its value is 4.
With respect to node 0, it is less than 4 so it goes to the left of 4
With respect to node 3, it is also less than 4 so it also goes to the left of 4
For now both are pointing to same node i.e. 2
We do this again and we will get our answer.
'''
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
def yca(root, v1, v2):
result = root
x = root
y = root
while x is not None and y is not None:
if v1 > x.info:
x = x.right
elif v1 == x.info : pass
else: x = x.left
if v2 > y.info:
y = y.right
elif v2 == y.info : pass
else: y = y.left
if x == y: result = x
else: break
return result
tree = BinarySearchTree()
total = 25
values = [23, 16, 15, 9 ,6, 17, 10, 13, 8, 26, 18, 2, 22, 24, 12, 5, 20, 25, 21, 4, 19, 1, 3, 14, 7]
for i in range(total):
tree.create(values[i])
nodes = [23,3]
result = yca(tree.root, nodes[0], nodes[1])
print (result.info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment