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.