Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Lowest Common Ancestor - Python Question

Challenges • Asked over 5 years ago by Devesh Kumar Singh

Devesh Kumar Singh Commented on Dec 23, 2019:

Test case tree2 is not valid. tree2 cannot represent a binary search tree since
tree2 = Node(5)
tree2.left = Node(10)
tree2.right = Node(8)
violates the fact that left child should be smaller than root, but here left child is greater than root since 10 > 5

Link to problem: Lowest Common Ancestor.

Jun Commented on Jul 04, 2025:

Devesh is right if the challenge assumes a Binary Search Tree. That tree2 violates BST invariants (left root.val and q.val > root.val:
root = root.right
else:
return root
```

General binary tree LCA (no ordering assumptions):
python
def lca(root, p, q):
if not root or root == p or root == q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
return root if left and right else left or right

So either update tree2 to be a valid BST, or clarify the challenge is for a general binary tree and don’t use BST-specific logic.