Find the deepest original tree node that is an ancestor of both given target nodes.
Problem
Input. A finite strict binary search tree and two target references that are actual nodes in that tree.
Output. Return their lowest common ancestor as the original node object, not a value or copied node.
Rules. Values are unique integers, with no cycles or shared children. A node counts as its own ancestor. The targets may be identical or one may be the other’s ancestor. Both targets must exist; missing targets require the checked variant below. Preserve the tree.
Example. In a BST with root 6 and children 2 and 8, those children have common ancestor node 6. If node 4 lies below node 2, targets 2 and 4 instead return node 2.
Picture
Keep targets three and five fixed while the current root changes.
| Current root | Target comparisons | Decision |
|---|---|---|
| 6 | Both smaller | Move left to 2 |
| 2 | Both larger | Move right to 4 |
| 4 | 3 < 4 < 5 | Return this node |
Problem trace
Stop where the targets split, or where one equals the current node
Original coordinate inventory
- root
- (0, 3)
- first
- (6, 1)
- second
- (6, 3)
Original coordinate inventory
- root
- (0, 3)→(2, 1)
- current root
- root=6→root=2
- decision
- both smaller -> move left to 2→both larger -> move right to 4
Original coordinate inventory
- root
- (2, 1)→(4, 2)
- current root
- root=2→root=4
- comparison
- not shown→3 < 4 < 5
Original coordinate inventory
- current root
- root=4→split: return 4
- path
- not shown→6 -> 2 -> 4
- result
- not shown→4
- Recognize it
- Both target nodes are in a BST, so comparing both values with the current root reveals whether their lowest common ancestor must be entirely left, entirely right, or current.
- Keep true
- At the start of every loop iteration, the current root’s subtree contains both targets; moving only when both values are on the same side preserves that fact.
- Reuse it
- In an ordered search tree, track where multiple target values fall relative to the current separator; the first separator they do not share is their lowest common routing point.
Reference drawing
Problem trace
Stop where the targets split, or where one equals the current node
Execution trace
Original coordinate inventory
- root
- (0, 3)
- first
- (6, 1)
- second
- (6, 3)
Original coordinate inventory
- root
- (0, 3)→(2, 1)
- current root
- root=6→root=2
- decision
- both smaller -> move left to 2→both larger -> move right to 4
Original coordinate inventory
- root
- (2, 1)→(4, 2)
- current root
- root=2→root=4
- comparison
- not shown→3 < 4 < 5
Original coordinate inventory
- current root
- root=4→split: return 4
- path
- not shown→6 -> 2 -> 4
- result
- not shown→4
- Recognize it
- Both target nodes are in a BST, so comparing both values with the current root reveals whether their lowest common ancestor must be entirely left, entirely right, or current.
- Keep true
- At the start of every loop iteration, the current root’s subtree contains both targets; moving only when both values are on the same side preserves that fact.
- Reuse it
- In an ordered search tree, track where multiple target values fall relative to the current separator; the first separator they do not share is their lowest common routing point.
Code
Use this node type for a local run.
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: "TreeNode | None" = None
right: "TreeNode | None" = None
def lowest_common_ancestor_bst(
root: TreeNode, first: TreeNode, second: TreeNode
) -> TreeNode:
while True:
if first.val < root.val and second.val < root.val:
root = root.left
elif first.val > root.val and second.val > root.val:
root = root.right
else:
return root
Preserve Both Targets Together
At each iteration, the current subtree contains both targets. Moving only when both values choose one side preserves that fact.
If the routes split, no single child subtree can contain both targets. The current node is therefore the lowest shared ancestor.
If a target equals the current root, that root is already the answer. For targets four and five, return four.
The returned object is an existing node, not a copied value. Neither target nor any tree link changes.
Time is for tree height ; auxiliary space is . An unbalanced BST can have linear height.
Do Not Infer Membership from a Split
The function compares values but never verifies target membership. An absent target can produce an unsupported split or reach None.
For example, two and absent value 99 split at root six. That does not prove both targets exist.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why not move according to only one target? That move could discard the other and break containment.
Check Possibly Absent Values
Choose this when: Callers supply values without promising membership.
Find both actual nodes first. Return None if either search fails; otherwise reuse the original node-based search.
def lca_present_values(root, first_value, second_value):
def find(value):
node = root
while node and node.val != value:
node = node.left if value < node.val else node.right
return node
first, second = find(first_value), find(second_value)
if first is None or second is None:
return None
return lowest_common_ancestor_bst(root, first, second).val
The interface returns an ancestor value rather than a node object. Values three and five return four; two and 99 return None.
Two membership searches and one ancestor search still take total time and auxiliary space.
Strict unique values remain required. Equal-valued but distinct nodes need a different identity and duplicate-placement contract.
Remove the Ordering Assumption
Choose this when: The input is a general unique-valued binary tree and both values must be present.
Every subtree returns a presence mask and any lowest complete ancestor already found.
Bit one records the first target; bit two records the second. Mask three certifies both, including one node serving both roles.
def general_lca_values(root, first_value, second_value):
def visit(node):
if node is None:
return None, 0
left_result, left_mask = visit(node.left)
right_result, right_mask = visit(node.right)
own = (1 if node.val == first_value else 0) | (2 if node.val == second_value else 0)
mask = left_mask | right_mask | own
result = left_result or right_result or (node if mask == 3 else None)
return result, mask
result, mask = visit(root)
return result.val if mask == 3 else None
A lower completed result takes priority over its ancestor. Without one, the current node becomes the answer once its combined mask reaches three.
This visits all nodes in time with recursive stack space. Deep trees can exceed Python’s recursion limit.