Skip to content

Commit 3fd2852

Browse files
authored
LCA in BinarySearchTree
1 parent 7723e6d commit 3fd2852

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Trees/P07_LCAinBST.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Lowest Common Ancestor in Binary search tree
2+
3+
class node:
4+
def __init__(self,key):
5+
self.key=key
6+
self.left=None
7+
self.right=None
8+
9+
def lca(root,n1,n2):
10+
if root is None:
11+
return None
12+
13+
if root.key<n1 and root.key<n2:
14+
return lca(root.right,n1,n2)
15+
16+
if root.key>n1 and root.key>n2:
17+
return lca(root.left,n1,n2)
18+
19+
return root
20+
21+
# Consider the following BST
22+
23+
# 8
24+
# / \
25+
# 3 11
26+
# / \ / \
27+
# 2 6 10 13
28+
# / \ /
29+
# 5 7 12
30+
31+
# Create BST
32+
root = node(8)
33+
l = root.left = node(3)
34+
r = root.right = node(11)
35+
r.left = node(10)
36+
r.right = node(13)
37+
r.right.left = node(12)
38+
l.left = node(2)
39+
l.right = node(6)
40+
l.right.left = node(5)
41+
l.right.right = node(7)
42+
43+
print(lca(root,2,7).key) # ouputs '3'

0 commit comments

Comments
 (0)