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

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