Same Tree

Given the roots p and q of two binary trees, return true if the trees are identical: they have exactly the same shape, and the nodes at matching positions hold equal values. Otherwise return false.

Either tree may be empty. Two empty trees are identical.

Constraints

  • Each tree has between 0 and 100 nodes.
  • -10^4 <= Node.val <= 10^4

Examples

Example 1

Input: p = [1,2,3], q = [1,2,3]
Output: true

Same shape and same value at every position.

Example 2

Input: p = [1,2], q = [1,null,2]
Output: false

Both trees hold 1 and 2, but 2 is the left child in one and the right child in the other: different shapes.

Example 3

Input: p = [1,2,1], q = [1,1,2]
Output: false

The shapes match but the values at the two child positions are swapped.

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} p
 * @param {TreeNode} q
 * @return {boolean}
 */
function isSameTree(p, q) {
  
}

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.