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
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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).