SDE & MLE Prep

572. Subtree of Another Tree

Problem

Decide whether subRoot appears in root as a subtree: some node of root together with all of its descendants is identical to subRoot.

Example: root = [3,4,5,1,2], subRoot = [4,1,2] → true; with an extra 0 under the 2 in root → false

For every node of root, check isSameTree(node, subRoot). (O(m+n) alternative: serialize both and do substring search / hashing.)

Complexity: O(m·n) worst case.

class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def same(a, b):
            if not a or not b:
                return a is b
            return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)

        if not root:
            return False
        return same(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)