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