Given two binary trees, decide whether the second appears as a subtree of the first (same structure and values from some node down). Then optimise your solution.
EasyGiven the roots of two binary trees, root and sub_root, return true if root contains a subtree with exactly the same shape and values as sub_root, and false otherwise.
A subtree of root is any node in root together with all of its descendants. A tree also counts as a subtree of itself.
Trees in the examples and tests are written in level order, with null for a missing child.
Example 1
Input: root = [3, 4, 5, 1, 2], sub_root = [4, 1, 2] Output: true
The node 4 in root has children 1 and 2, matching sub_root exactly.
Example 2
Input: root = [3, 4, 5, 1, 2, null, null, null, null, 0], sub_root = [4, 1, 2] Output: false
The node 4 in root has an extra descendant, 0, so its subtree doesn't match.
Constraints
roothas between1and2000nodes, andsub_roothas between1and1000nodes.-10^4 <= Node.val <= 10^4
Approach
Any match has to start at some node of root, so visit every node and ask whether the tree starting there is identical to sub_root. The identical-tree check is the usual recursion: empty matches empty, an empty node never matches a non-empty one, and otherwise the values and both pairs of children have to match. If no node in root produces a match, the answer is false.
Steps
- If
rootis empty, returnfalse. - If the tree starting at
rootis the same assub_root, returntrue. - Otherwise, return whether
sub_rootis a subtree ofroot.leftor ofroot.right.
Complexity
- Time:
O(m · n)in the worst case, wheremandnare the sizes of the two trees. Each node ofrootcan start a comparison that walks all ofsub_root. - Space:
O(h)for the recursion stack, wherehis the height ofroot.
Common mistakes
- Accepting a match when only the top of the tree agrees. The subtree in
roothas to end exactly wheresub_rootends, with no extra descendants. - Writing trees as strings without separators.
[12]and[2]would give12and2, and2appears inside12, even though neither tree contains the other.
Related courses

