The user wants a program to find the Lowest Common Ancestor (LCA) in a Binary Search Tree (BST).
Understand the Problem:
Input: A BST (root node), and two nodes (let's call them p and q) that exist in the tree.
Output: The node that is the deepest ancestor of both p and q.
Constraint/Benefit: It's a Binary Search Tree, not just a generic binary tree. This is crucial.
In a generic binary tree, finding LCA requires traversing paths or recursion (Time complexity O(N)).
In a BST, the values are ordered:
Left Subtree < Node < Right Subtree.
Logic for BST:
If both p and q are smaller than the current node, the LCA must be in the left subtree.
If both p and q are larger than the current node, the LCA must be in the right subtree.
If one is smaller and the other is larger (or equal to) the current node, then the current node is the LCA (the split point).
Determine the Approach:
Iterative Approach: Usually better for space complexity (O(1)) compared to recursion (O(H) stack space, where H is height).
Recursive Approach: Also valid and often easier to read for some.
I will provide the Iterative approach as the primary solution because it's more efficient in terms of space, but I might briefly mention recursion or just stick to the most standard "interview-ready" solution which is often iterative.
Select a Programming Language: Python is generally the most pseudo-code-like and easy to understand. I should also provide the Node definition to make the code runnable.
Drafting the Code (Mental Draft):
python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def lowestCommonAncestor(root, p, q):
current = root
while current:
# If both p and q are greater, go right
if p.val > current.val and q.val > current.val:
current = current.right
# If both p and q are smaller, go left
elif p.val < current.val and q.val < current.val:
current = current.left
else:
# We found the split point
return current
return None # Should theoretically not happen if p and q exist
Refining the Code:
The logic looks solid.
Need to handle edge cases? The problem implies nodes exist. If nodes might not exist, we'd need a search function first, but standard LCA problems usually assume existence. I will stick to the standard LeetCode-style assumption that nodes exist.
What if p is the ancestor of q? The logic holds. E.g., root is 6, p=6, q=4.
Iteration 1: current = 6. p(6) not > 6, q(4) not > 6. p(6) not < 6, q(4) < 6 (wait, logic error in strict inequality).
Correction: If p is the ancestor of q, current will eventually be p. If p.val == current.val, the "else" block triggers. That works.
Example: Root=2, p=2, q=1.
Check p > curr (2>2 False) and q > curr (1>2 False).
Check p < curr (2<2 False). Logic goes to else. Returns 2. Correct.
Structuring the Explanation:
Definition: Define the Node class.
Algorithm: Explain why the BST property simplifies this (the "split point").
Code: Provide the Python solution.
Complexity Analysis: Time (O(h) or O(logn)) and Space (O(1)).
Example: A quick usage example to show it running.
Code Construction (Final Polish):
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
# Ensure p is the smaller one for easier comparison logic (optional but clean)
# Actually, standard iterative is fine without swapping.
current = root
while current:
if p.val > current.val and q.val > current.val:
current = current.right
elif p.val < current.val and q.val < current.val:
current = current.left
else:
return current
return None
Alternative Language?
Some users prefer C++ or Java. I'll stick to Python as the default "write a program" response unless specified, but maybe I should write it in a way that translates easily. Python is the safest bet for clarity. I will provide just Python to keep it clean, as it's the most common request language.
Review against prompt: "Write a program that finds the lowest common ancestor in a binary search tree."
The provided solution covers exactly this.
Final Output Generation:
Start with the core logic explanation.
Provide the code.
Provide an example usage.
Briefly explain complexity.
(Self-Correction during drafting):
Should I handle the case where p and q are swapped (p > q)? The code if p > root and q > root works regardless of which is larger.
Example: Root=6. p=2, q=8.
p(2) < 6, q(8) > 6. Neither if condition is met. else returns 6. Correct.
Example: Root=6. p=3, q=4.
p(3) < 6, q(4) < 6. elif condition met. Move left. Correct.
The code is robust.
Let's produce the response.
Here is a solution in Python.
The Logic
In a Binary Search Tree (BST), the Lowest Common Ancestor (LCA) of two nodes p and q is the first node you encounter where one target node is in the left subtree and the other is in the right subtree.
Because a BST is sorted:
If both p and q are smaller than the current node, the LCA must be in the left subtree.
If both p and q are larger than the current node, the LCA must be in the right subtree.
Otherwise (if one is smaller and one is larger, or one equals the current node), you have found the split point, which is the LCA.
Python Implementation
python
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 of two nodes in a Binary Search Tree.
"""
current = root
while current:
# Case 1: Both p and q are smaller than current.
# The LCA must be in the left subtree.
if p.val < current.val and q.val < current.val:
current = current.left
# Case 2: Both p and q are larger than current.
# The LCA must be in the right subtree.
elif p.val > current.val and q.val > current.val:
current = current.right
# Case 3: We found the divergence point.
# This happens if:
# a) p and q split directions (one left, one right)
# b) current equals p or q
else:
return current
return None
Example Usage
Here is how you can create a tree and test the function:
python
# 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)
# Nodes to find LCA for
node_p = root.left # Value 2
node_q = root.left.right # Value 4
# Find LCA
lca = lowest_common_ancestor(root, node_p, node_q)
print(f"LCA of {node_p.val} and {node_q.val} is: {lca.val}")
# Output should be 2
Complexity Analysis
Time Complexity:O(h), where h is the height of the tree. In a balanced tree, this is O(logn). In the worst case (a skewed line tree), it is O(n).
Space Complexity:. We only use a few pointers for iteration, so no extra memory is allocated for stacks or recursion.