Lowest Common Ancestor of a Binary Tree
LeetCode 236 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
left + right + self ≥ 2 ⇒ LCA.
నేను 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
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.
నేను ఎలా పరిష్కరించాను
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.ansLowest 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).