-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLowest_common_ancestor
40 lines (40 loc) · 1.2 KB
/
Lowest_common_ancestor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Node:
def __init__(self,key):
self.left=None
self.right=None
self.value=key
class BinaryTree:
def __init__(self):
self.root1=None
#used to the tree from class Node and its object root
def _inorder_recursive(self,node):
if node:
self._inorder_recursive(node.left)
print(node.value,end="->")
self._inorder_recursive(node.right)
#LOWEST COMMON ANCESTOR
def lca(self,root,n1,n2):
if root is None:
return None
if root.value==n1 or root.value==n2:
return root
left_lca=self.lca(root.left,n1,n2)
right_lca=self.lca(root.right,n1,n2)
if left_lca and right_lca:
return root
return left_lca if left_lca is not None else right_lca
#Create nodes
root=Node(10)
root.left=Node(34)
root.right=Node(20)
root.left.left=Node(3)
root.left.right=Node(4)
root.right.left=Node(12)
root.right.right=Node(54)
tree=BinaryTree()
tree.root1=root
print(tree._inorder_recursive(tree.root1))
print(tree.height(tree.root1))
n1,n2=3,4
ancestor=tree.lca(tree.root1,n1,n2)
print("Lowest Common Ancestor of nodes {n1} and {n2}:",ancestor.value if ancestor else "None")