Subtree of Another Tree – Solution & Complexity

Solution Walkthrough

  1. Step 1: Decompose into Same Tree + DFS

    • A tree subRoot is a subtree of root if either:
      1. root and subRoot are the exact same tree, or
      2. subRoot is a subtree of root.left, or
      3. subRoot is a subtree of root.right.
    • Write a small helper is_same(a, b) that checks value equality and recurses on both children.
  2. Step 2: Handle duplicate node values carefully

    • Do not stop searching if root.val == subRoot.val and is_same(root, subRoot) returns False — a matching subtree may still sit deeper down (for example root = [1, 1], subRoot = [1]).
  3. Step 3: Clean recursive solution

    • Time complexity: O(m * n) in the worst case where m = |root| and n = |subRoot|. Space complexity: O(h) for the recursion stack.
    def is_subtree(root: TreeNode, subRoot: TreeNode) -> bool:
        def is_same(a, b):
            if not a and not b:
                return True
            if not a or not b or a.val != b.val:
                return False
            return is_same(a.left, b.left) and is_same(a.right, b.right)
    
        if not subRoot:
            return True
        if not root:
            return False
        if is_same(root, subRoot):
            return True
        return is_subtree(root.left, subRoot) or is_subtree(root.right, subRoot)
  4. Step 4: Common mistakes

    • Returning is_same(root, sub_root) immediately when root.val == sub_root.val instead of continuing to search the children on mismatch.
    • Serializing without a leading delimiter (e.g. 12 matching 2 as a substring).

FAQ