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