Given the roots of two binary trees, root
and subRoot
, determine whether subRoot
is a subtree of root
. The function should return true
if there exists a subtree within root
that has the same structure and node values as subRoot
. If no such subtree exists, return false
.
The binary tree is represented by a collection of TreeNode
s, where each node has optional left
and right
child nodes, which are also TreeNode
s.
A TreeNode
has the following interface:
interface TreeNode {val: number;left: TreeNode | null;right: TreeNode | null;}
root: TreeNode
: Root node of the tree. Examples display a level-order traversal of the treesubRoot: TreeNode
: Root node of the subtree. Examples display a level-order traversal of the treeInput: root = [1,2,3], subRoot = [1,2]Output: falseExplanation: SubRoot cannot be a subtree since the root node structure differs.
Input: root = [12,8,6,3,5], subRoot = [8,3,5]Output: trueExplanation: The subtree rooted at node 8 matches subRoot.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,null,5,1], subRoot = [11,7,2,5,1]Output: trueExplanation: The subtree rooted at node 11 matches subRoot.
TreeNode.val
<= 10,000Given the roots of two binary trees, root
and subRoot
, determine whether subRoot
is a subtree of root
. The function should return true
if there exists a subtree within root
that has the same structure and node values as subRoot
. If no such subtree exists, return false
.
The binary tree is represented by a collection of TreeNode
s, where each node has optional left
and right
child nodes, which are also TreeNode
s.
A TreeNode
has the following interface:
interface TreeNode {val: number;left: TreeNode | null;right: TreeNode | null;}
root: TreeNode
: Root node of the tree. Examples display a level-order traversal of the treesubRoot: TreeNode
: Root node of the subtree. Examples display a level-order traversal of the treeInput: root = [1,2,3], subRoot = [1,2]Output: falseExplanation: SubRoot cannot be a subtree since the root node structure differs.
Input: root = [12,8,6,3,5], subRoot = [8,3,5]Output: trueExplanation: The subtree rooted at node 8 matches subRoot.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,null,5,1], subRoot = [11,7,2,5,1]Output: trueExplanation: The subtree rooted at node 11 matches subRoot.
TreeNode.val
<= 10,000console.log()
statements will appear here.