Lowest Common Ancestor in Binary Search Tree
class TreeNode(object):
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def __repr__(self):
return str(self.value)
class Solution(object):
def find_LCA(self,root,node1,node2):
if node1.value<=node2.value:
return self.__find_LCA(root,node1,node2)
else:
return self.__find_LCA(root,node2,node1)
def __find_LCA(self,root,node1,node2):
while root.value <node1.value or root.value>node2.value:
while root.value <node1.value:
root = root.right
while root.value > node2.value:
root = root.left
return root
Binary Search Tree is special case of Binary Tree where we have ordering of nodes. We can take adavantage of this ordering property .
Time Complexity O(h) h is heaight of BST