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).