Binary Tree Subtree

Languages

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.

Notes

  • A subtree is defined as a portion of a binary tree that includes a node and all of its descendants
  • A tree can be considered a subtree of itself

The binary tree is represented by a collection of TreeNodes, where each node has optional left and right child nodes, which are also TreeNodes.

A TreeNode has the following interface:

interface TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
}

Input

Examples

Input: root = [1,2,3], subRoot = [1,2]
Output: false
Explanation: SubRoot cannot be a subtree since the root node structure differs.
Input: root = [12,8,6,3,5], subRoot = [8,3,5]
Output: true
Explanation: 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: true
Explanation: The subtree rooted at node 11 matches subRoot.

Constraints

  • 1 <= Number of nodes <= 100
  • -10,000 <= TreeNode.val <= 10,000