|  | 
|  | 1 | +""" | 
|  | 2 | + Given a binary search tree, determine the lowest common ancestor of two given nodes with data | 
|  | 3 | + key1 and key2. Assumption is key1 and key2 exists in tree | 
|  | 4 | + Example | 
|  | 5 | +           20 | 
|  | 6 | +       /        \ | 
|  | 7 | +       8        22 | 
|  | 8 | +   /      \ | 
|  | 9 | +   4        12 | 
|  | 10 | +         /     \ | 
|  | 11 | +       10     14 | 
|  | 12 | +In the above tree, LCA of 10 and 14 is 12 | 
|  | 13 | +similarly 4 and 22 will have LCA 20 | 
|  | 14 | +""" | 
|  | 15 | + | 
|  | 16 | +class Node: | 
|  | 17 | +    def __init__(self, data): | 
|  | 18 | +        """Binary Search Tree Node representation""" | 
|  | 19 | +        self.data = data | 
|  | 20 | +        self.left = None | 
|  | 21 | +        self.right = None | 
|  | 22 | + | 
|  | 23 | + | 
|  | 24 | +def LCA(root, key1, key2): | 
|  | 25 | +    if root is None: | 
|  | 26 | +        return None | 
|  | 27 | + | 
|  | 28 | +    if root.data > key1 and root.data > key2: | 
|  | 29 | +        return LCA(root.left, key1, key2) | 
|  | 30 | + | 
|  | 31 | +    elif root.data < key1 and root.data < key2: | 
|  | 32 | +        return LCA(root.right, key1, key2) | 
|  | 33 | + | 
|  | 34 | +    return root | 
|  | 35 | + | 
|  | 36 | +def inorder(root): | 
|  | 37 | +    if root is None: | 
|  | 38 | +        return | 
|  | 39 | +    inorder(root.left) | 
|  | 40 | +    print(root.data, end =' ') | 
|  | 41 | +    inorder(root.right) | 
|  | 42 | + | 
|  | 43 | + | 
|  | 44 | + | 
|  | 45 | +if __name__ == "__main__": | 
|  | 46 | +    root = Node(20) | 
|  | 47 | +    root.right = Node(22) | 
|  | 48 | +    root.left = Node(8) | 
|  | 49 | +    root.left.left = Node(4) | 
|  | 50 | +    root.left.right= Node(12) | 
|  | 51 | +    root.left.right.right = Node(14) | 
|  | 52 | +    root.left.right.left = Node(10) | 
|  | 53 | +    print("Inorder traversal of the tree:") | 
|  | 54 | +    inorder(root); | 
|  | 55 | +    print() | 
|  | 56 | +    print("LCA of nodes with data 10 and 14 is :") | 
|  | 57 | +    print(LCA(root, 14, 10).data); | 
|  | 58 | +    print("LCA of nodes with data 14 and 8 is :") | 
|  | 59 | +    print(LCA(root, 14, 8).data); | 
|  | 60 | +    print("LCA of root with data 4 and 22 is :") | 
|  | 61 | +    print(LCA(root, 4, 22).data); | 
|  | 62 | +    print("LCA of root with data 14 and 10 is :") | 
|  | 63 | +    print(LCA(root, 10, 14).data); | 
0 commit comments