Tensorum
YouTubeশেখা শুরু করুন
LeetCode 235 · BST

Lowest Common Ancestor of a Binary Search Tree

LeetCode 235 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Walk down until p and q split.

মাঝারিTreeDepth-First SearchBinary Search TreeBinary TreeBinary Lifting
LeetCode-এ খুলুন ↗

আমি 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. 1

    Current is p or q → return it.

  2. 2

    Both smaller → go left.

  3. 3

    Both larger → go right.

  4. 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 root
স্টেপ-থ্রু লোড হচ্ছে…

Lowest 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.