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.