1. Understand the Goal: The user wants a program to find the Lowest Common Ancestor (LCA) in a Binary Search Tree (BST).
-
Identify the Key Concepts:
- Binary Search Tree (BST): A tree data structure where for every node N:
- All values in the left subtree are less than N.val.
- All values in the right subtree are greater than N.val.
- Lowest Common Ancestor (LCA): Given two nodes p and q, the LCA is the lowest node in the tree that has both p and q as descendants (a node can be a descendant of itself).
-
Determine the Algorithm:
- Input: Root of the BST, node p, node q.
- Logic: Utilize the BST property.
- If both p and q are smaller than the current node, the LCA must be in the left subtree.
- If both p and are larger than the current node, the LCA must be in the subtree.
-
Select the Language: Python is generally the most readable and widely used for algorithmic examples. I will also provide a C++ or Java version if it seems helpful, but Python is usually the best default. Let's stick to Python for clarity, maybe add a recursive and an iterative version.
-
Drafting the Python Code:
-
Node Definition:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
-
Iterative Approach (Space Efficiency):
def lowestCommonAncestor(root, p, q):
current = root
while current:
if p.val < current.val and q.val < current.val:
current = current.left
elif p.val > current.val and q.val > current.val:
current = current.right
else:
return current
-
Recursive Approach:
def lowestCommonAncestor(root, p, q):
if p.val < root.val and q.val < root.val:
return lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return lowestCommonAncestor(root.right, p, q)
else:
return root
-
Structuring the Output:
- Start with a brief explanation of the logic (BST property).
- Provide the code (I'll provide the Iterative solution as it's slightly more robust/efficient regarding stack depth, but I'll mention the recursive logic). Actually, providing both or the cleaner one is better. The iterative one is often preferred in production to avoid stack overflow on deep trees.
- Include a driver code to demonstrate how to use it. This makes the answer copy-paste runnable.
-
Refining the Explanation:
- Explain why it works: We traverse the tree from the root. As long as both values are on one side, we move there. The moment they split (one left, one right) or one matches the current node, that node is the ancestor.
-
Final Code Check:
- Class definition included? Yes.
- Function signature standard? Yes.
- Handling the logic correctly?
p < curr and q < curr -> Go Left.
p > curr and q > curr -> Go Right.
- Else -> Return
curr.
- Does it handle the case where one node is the parent of the other? Yes, the logic covers the "split" including equality implicitly (if p=curr, then it's not true that p<curr or , so it falls into ).
-
Constructing the Response: (This matches the provided good response).
- Language: Python.
- Approach: Iterative (Best practice).
- Add comments.
- Add test case.
-
Self-Correction during drafting: Should I include type hinting? Yes, it makes code look professional.
def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
-
Final output generation. (Proceed to generate Python code).
Here is a solution in Python.
This solution utilizes the properties of a Binary Search Tree (BST), where for any given node:
- All values in the left subtree are smaller than the node's value.
- All values in the right subtree are larger than the node's value.
The Logic
We traverse the tree starting from the root:
- Go Left: If both target nodes (
p and q) are smaller than the current node, the LCA must be in the left subtree.
- Go Right: If both target nodes are larger than the current node, the LCA must be in the right subtree.
- Found It: If the nodes are on different sides (one smaller, one larger), or if one node equals the current node, we have found the Lowest Common Ancestor.
The Code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lowest_common_ancestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
"""
Finds the Lowest Common Ancestor (LCA) of two nodes in a BST.
"""
current = root
while current:
# If both p and q are smaller than current, LCA is in the left subtree
if p.val < current.val and q.val < current.val:
current = current.left
# If both p and q are larger than current, LCA is in the right subtree
elif p.val > current.val and q.val > current.val:
current = current.right
# We have found the split point (or match), this is the LCA
else:
return current
return None
# --- Helper Code to Test the Solution ---
if __name__ == "__main__":
# Constructing the following BST:
# 6
# / \
# 2 8
# / \ / \
# 0 4 7 9
# / \
# 3 5
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(8)
root.left.left = TreeNode(0)
root.left.right = TreeNode(4)
root.right.left = TreeNode(7)
root.right.right = TreeNode(9)
root.left.right.left = TreeNode(3)
root.left.right.right = TreeNode(5)
# Example 1: LCA of 2 and 8 should be 6
p = root.left # Node with val 2
q = root.right # Node with val 8
lca = lowest_common_ancestor(root, p, q)
print(f"LCA of {p.val} and {q.val} is: {lca.val}") # Output: 6
# Example 2: LCA of 2 and 4 should be 2
p = root.left # Node with val 2
q = root.left.right # Node with val 4
lca = lowest_common_ancestor(root, p, q)
print(f"LCA of {p.val} and {q.val} is: {lca.val}") # Output: 2
Complexity Analysis
- Time Complexity: O(H), where H is the height of the tree. In the worst case (a skewed tree), this is O(N), but for a balanced BST, it is O(logN).
- Space Complexity: . We only use a few pointers for tracking the current node, so no extra memory is allocated for stacks or recursion.