Determine whether one binary tree appears as a subtree of another binary tree.
Problem
Given the roots of two binary trees root and subRoot, determine whether subRoot is a subtree of root.
A tree subRoot is considered a subtree of root if there exists a node in root such that the entire tree rooted at that node has the same structure and node values as subRoot.
Two trees are the same when they are both empty or when their roots have equal values and their left and right subtrees are also the same.
Goal
Return true if subRoot is a subtree of root; otherwise, return false.
Input Format
Input Format
- Two binary tree roots:
rootandsubRoot. - Each tree node contains an integer value and optional left/right children.
Output Format
Output Format
- Return a boolean value:
trueifsubRootis a subtree ofrootfalseotherwise
Constraints
Constraints
- The trees may be empty.
- Node values are integers.
- You may assume the trees fit in memory.
- A valid solution should avoid unnecessary re-computation when checking repeated candidate nodes.
Example 1
Input
root = [3,4,5,1,2], subRoot = [4,1,2]
Output
true
Explanation
The tree rooted at the node with value 4 has the same structure and values as subRoot.
Example 2
Input
root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output
false
Explanation
Although root contains a node with value 4, its subtree does not match subRoot because of the extra node 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.