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.