Subtree of Another Tree

You are given the roots of two binary trees, root and subRoot. Return true if some node of root is the top of a tree that is identical to subRoot: same shape and same values, including every descendant of that node. Otherwise return false.

The tree root itself counts as a subtree of itself. A node together with only some of its descendants does not count.

Constraints

  • root has between 0 and 2000 nodes, subRoot between 1 and 1000.
  • -10^4 <= Node.val <= 10^4
  • Values may repeat.

Examples

Example 1

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

The subtree rooted at 4 is exactly 4 with children 1 and 2.

Example 2

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

The node 4 has the right values, but its child 2 has an extra child 0 below it. A subtree must include all descendants, so this does not match.

Example 3

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

A single node 1 is the subtree rooted at the left child (which has no children).

JavaScript you'll use: Recursion, the call stack and memoization Linked list and tree nodes

/**
 * Tree nodes are provided (you don't need to define them):
 * class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} subRoot
 * @return {boolean}
 */
function isSubtree(root, subRoot) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.