Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 236 · Lowest Common Ancestor / Distance

Lowest Common Ancestor of a Binary Tree

LeetCode 236 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

left + right + self ≥ 2 ⇒ LCA.

मध्यमTreeDepth-First SearchBinary TreeBinary LiftingLowest Common Ancestor

मी Lowest Common Ancestor of a Binary Tree (LeetCode 236) असा सोडवला — Lowest Common Ancestor / Distance पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Ask each node: does my subtree contain p or q? A node counts itself (if it's p or q) plus what its left and right subtrees found. The first node where at least two of those three are true is the lowest common ancestor.

Approach

  1. 1

    dfs returns whether p or q is in the subtree.

  2. 2

    left, right from children; mid = node is p or q.

  3. 3

    If left + right + mid ≥ 2, record node.

  4. 4

    Return whether any of them is true.

मी कसा सोडवला

Post-order countingPythonO(n) time · O(h) space
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        self.ans = None

        def dfs(node):
            if node is None:
                return False
            left = 1 if dfs(node.left) else 0
            right = 1 if dfs(node.right) else 0
            mid = 1 if (node == p or node == q) else 0
            if left + right + mid >= 2:
                self.ans = node
            return left + right + mid > 0
        dfs(root)
        return self.ans
स्टेप-थ्रू लोड होत आहे…

Lowest Common Ancestor of a Binary Tree — वारंवार विचारले जाणारे प्रश्न

Lowest Common Ancestor of a Binary Tree मागील intuition काय आहे?

Ask each node: does my subtree contain p or q? A node counts itself (if it's p or q) plus what its left and right subtrees found. The first node where at least two of those three are true is the lowest common ancestor.

Lowest Common Ancestor of a Binary Tree (LeetCode 236) कसा सोडवावा?

1. dfs returns whether p or q is in the subtree. 2. left, right from children; mid = node is p or q. 3. If left + right + mid ≥ 2, record node. 4. Return whether any of them is true.

Lowest Common Ancestor of a Binary Tree ची time आणि space complexity किती आहे?

Time: O(n). Space: O(h). (Accepted approach: Post-order counting.)

Lowest Common Ancestor of a Binary Tree मध्ये सामान्य चुका कोणत्या?

A node can be its own ancestor (p is the ancestor of q).