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

मैंने 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.