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