☰ All problems

39. Same Tree

You are given the roots p and q of two binary trees. Return true if they are identical: the same shape, with equal values in every matching position. Otherwise return false.

Two empty trees count as identical.

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

Explanation: In p the 2 is a left child, in q it is a right child. The values match but the shapes do not.

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

Constraints

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

Compare the two roots first. What must be true about them before looking deeper?

💡 Hint 2

If both nodes are null the trees match here; if exactly one is null they do not. Otherwise the values must be equal and both pairs of children must match recursively.

/**
 * Definition for a binary tree node (provided):
 * function TreeNode(val, left, right) { this.val = val ?? 0; this.left = left ?? null; this.right = right ?? null; }
 *
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
function isSameTree(p, q) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc