Binary Search Tree : Lowest Common Ancestor

  • + 0 comments
    def get_chain(root, val, chain):
        if not root:
            return None
        if root.info == val:
            chain = chain + (root,)
            return chain
        left_result = get_chain(root.left, val, chain)
        if left_result:
            return left_result + (root,)
        right_result = get_chain(root.right, val, chain)
        if right_result:
            return right_result + (root,)
        return chain
    
    
    def lca(root, v1, v2):
        x = get_chain(root, v1, ())
        y = get_chain(root, v2, ())
        x = list(x)
        y = set(y)
        common = None
        for i in range(len(x)):
            if x[-(i+1)] in y:
                common = x[-(i+1)]
        return common