Subtree of Another Tree – Solution & Complexity
Solution Walkthrough
Step 1: Decompose into Same Tree + DFS
- A tree
subRootis a subtree ofrootif either:rootandsubRootare the exact same tree, orsubRootis a subtree ofroot.left, orsubRootis a subtree ofroot.right.
- Write a small helper
is_same(a, b)that checks value equality and recurses on both children.
- A tree
Step 2: Handle duplicate node values carefully
- Do not stop searching if
root.val == subRoot.valandis_same(root, subRoot)returnsFalse— a matching subtree may still sit deeper down (for exampleroot = [1, 1],subRoot = [1]).
- Do not stop searching if
Step 3: Clean recursive solution
- Time complexity:
O(m * n)in the worst case wherem = |root|andn = |subRoot|. Space complexity:O(h)for the recursion stack.
- Time complexity:
Step 4: Common mistakes
- Returning
is_same(root, sub_root)immediately whenroot.val == sub_root.valinstead of continuing to search the children on mismatch. - Serializing without a leading delimiter (e.g.
12matching2as a substring).
- Returning
Part of Blind 75 · NeetCode 150