Blind 75 · Trees

Subtree of Another Tree

Easy

Watch the walkthrough (6:14)

Problem

The input is root and subRoot, the roots of two binary trees.
A subtree of root is a node of root with everything below it.
Return true if some subtree of root has the same shape and values as subRoot, and false if none does.
The whole of root counts as a subtree too.

Examples

Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true

Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
Explanation: the matching 4 now has an extra 0 hanging under its 2 — all descendants count.

Example 3:
Input: root = [1,1], subRoot = [1]
Output: true

Example 4:
Input: root = [3,4,5,1,2], subRoot = [3]
Output: false

Constraints

1 <= nodes in root <= 2000
1 <= nodes in subRoot <= 1000
-10^4 <= Node.val <= 10^4

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. Same Tree, Tried Everywhere Optimal

Intuition

This is the previous problem used as a subroutine: a candidate match can only start at a node whose value equals subRoot's, and from there the question is exactly "are these two trees identical". Saying that out loud — that you already have the hard part — is most of the answer.

Algorithm

1. Walk the main tree.
2. At each node, if an identical-trees check against subRoot passes, return true.
3. Otherwise try the left and right subtrees.
4. Running out of nodes means no match.

Time & Space

Time O(n*m) in the worst case, which passes at these sizes. The follow-up serializes both trees, with a separator around every value and a marker for every empty child, and searches for one string inside the other, O(n+m).

2. One Helper, Checks Joined

Intuition

The same search, with the same-tree check written as a helper of its own, identical, nested inside isSubtree in Python and a private method in Java, and its two checks that answer false joined in one if: one tree empty, or the two values different. The first approach calls Same Tree's own isSameTree instead, a line a check, so the previous problem's answer is used exactly as it was written; the work is the same.

Algorithm

1. Walk the main tree.
2. At each node, if an identical-trees check against subRoot passes, return true.
3. Otherwise try the left and right subtrees.
4. Running out of nodes means no match.

Time & Space

Time O(n*m) in the worst case, which passes at these sizes. The follow-up serializes both trees, with a separator around every value and a marker for every empty child, and searches for one string inside the other, O(n+m).