Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 572 · DFS Basics

Subtree of Another Tree

LeetCode 572 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

isSubtree = sameTree(root, sub) or recurse into children.

எளிதுTreeDepth-First SearchString MatchingBinary TreeHash Function
LeetCode இல் திற ↗

நான் 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. 1

    Empty root → False.

  2. 2

    If sameTree(root, subRoot), done.

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