Subtree of Another Tree
LeetCode 572 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
isSubtree = sameTree(root, sub) or recurse into children.
నేను Subtree of Another Tree (LeetCode 572) ను ఇలా పరిష్కరించాను — DFS Basics ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
For every node of the main tree, ask: is the tree rooted here the same as subRoot? Reuse the same-tree check.
Approach
- 1
Empty root → False.
- 2
If sameTree(root, subRoot), done.
- 3
Otherwise try root.left and root.right.
నేను ఎలా పరిష్కరించాను
Same-tree at every nodePythonO(m·n) time
class Solution:
def isSameTree(self, p, q):
if p is None and q is None:
return True
if p is None or q is None:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
def isSubtree(self, root, subRoot):
if root is None:
return False
if self.isSameTree(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)Subtree of Another Tree — తరచూ అడిగే ప్రశ్నలు
Subtree of Another Tree వెనుక ఉన్న intuition ఏమిటి?
For every node of the main tree, ask: is the tree rooted here the same as subRoot? Reuse the same-tree check.
Subtree of Another Tree (LeetCode 572) ను ఎలా పరిష్కరించాలి?
1. Empty root → False. 2. If sameTree(root, subRoot), done. 3. Otherwise try root.left and root.right.
Subtree of Another Tree యొక్క time, space complexity ఎంత?
Time: O(m · n). Space: O(h). (Accepted approach: Same-tree at every node.)
Subtree of Another Tree లో సాధారణ పొరపాట్లు ఏమిటి?
Matching values aren't enough — the whole structure below must match (example 2).