Binary Search Tree : Lowest Common Ancestor

  • + 1 comment
    from collections import deque
    
    def lca(root, v1, v2):
        if root is None: 
            return None
        
        # Find path from root to target node
        def findPathToTarget(root, target_int):
            dq = deque([(root, [])])
            while dq:
                node, path = dq.popleft()
                new_path = path + [node]  # Create a new path list
                if node.info == target_int:
                    return new_path
                if node.left:
                    dq.append((node.left, new_path))
                if node.right:
                    dq.append((node.right, new_path))
            return []
    
        # Get paths to v1 and v2
        path_to_v1 = findPathToTarget(root, v1)
        path_to_v2 = findPathToTarget(root, v2)
    
        # Compare paths to find LCA
        lca = None
        for a, b in zip(path_to_v1, path_to_v2):
            if a == b:
                lca = a
            else:
                break
        return lca