Lowest Common Ancestor of a Binary Search Tree
LeetCode 235 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Walk down until p and q split.
నేను Lowest Common Ancestor of a Binary Search Tree (LeetCode 235) ను ఇలా పరిష్కరించాను — BST ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.
Approach
- 1
Current is p or q → return it.
- 2
Both smaller → go left.
- 3
Both larger → go right.
- 4
Otherwise → current node.
నేను ఎలా పరిష్కరించాను
BST descentPythonO(h) time
class Solution:
def lowestCommonAncestor(self, root, p, q):
if root == p or root == q:
return root
cur = root.val
if cur > p.val and cur > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif cur < p.val and cur < q.val:
return self.lowestCommonAncestor(root.right, p, q)
return rootLowest Common Ancestor of a Binary Search Tree — తరచూ అడిగే ప్రశ్నలు
Lowest Common Ancestor of a Binary Search Tree వెనుక ఉన్న intuition ఏమిటి?
In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.
Lowest Common Ancestor of a Binary Search Tree (LeetCode 235) ను ఎలా పరిష్కరించాలి?
1. Current is p or q → return it. 2. Both smaller → go left. 3. Both larger → go right. 4. Otherwise → current node.
Lowest Common Ancestor of a Binary Search Tree యొక్క time, space complexity ఎంత?
Time: O(h). Space: O(h) recursion. (Accepted approach: BST descent.)
Lowest Common Ancestor of a Binary Search Tree లో సాధారణ పొరపాట్లు ఏమిటి?
An iterative loop uses O(1) space.