Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    Python. Should work for any tree not only binary search.

    def search(root, v):
        if root:
            if root.info == v:
                return root
            l = search(root.left, v)
            if l:
                return l
            r = search(root.right, v)
            if r:
                return r
            return None
                
    def lca(root, v1, v2):
    
        if search(root.left, v1) and search(root.left, v2):
            return lca(root.left, v1, v2)
        
        if search(root.right, v1) and search(root.right, v2):
            return lca(root.right, v1, v2)
        
        return root