You are given the roots of two binary trees, root and subRoot. Determine whether subRoot appears as a subtree of root.
A subtree consists of some node in root together with all of that node's descendants; it matches subRoot when their structures and node values are identical. Return true if such a matching subtree exists, otherwise false.
Example 1
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
The node with value 4 and its two children exactly match subRoot.
Example 2
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
The candidate subtree rooted at 4 now has an extra child (0), so it no longer matches subRoot.
Constraints
The number of nodes in the root tree is in the range [1, 2000].The number of nodes in the subRoot tree is in the range [1, 1000].-10^4 <= root.val <= 10^4-10^4 <= subRoot.val <= 10^4See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI