Skip to problem
←

Same Tree

Easy 0 attempts

Given the roots p and q of two binary trees, return whether they have exactly the same structure and matching values at every corresponding position.

Left and right positions matter: a left child does not match a right child. The nodes do not need to be the same objects; compare their values and child structure. Equal collections of values alone are not enough.

Two empty trees are the same. If exactly one tree is empty, they are different. For p = [1, 2] and q = [1, null, 2], return false because the node containing 2 is on a different side.

Examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement isSameTree(p, q). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return true when both trees have identical left/right structure and equal values at every corresponding node; otherwise return false.

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
Constraints
  • Each tree contains between 0 and 100 nodes.
  • -10^4 <= Node.val <= 10^4

Compare Corresponding Subtrees

If both roots are null, the two subtrees match. If just one is null, their shapes differ. If both exist but their values differ, reject immediately.

Otherwise compare left with left and right with right. Both comparisons must succeed. This recursively checks every corresponding value and missing-child position, rather than comparing only a traversal's values.

javascript
function isSameTree(p, q) {
  if (!p && !q) return true;
  if (!p || !q || p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

Time: O(n) worst case, where n is the total number of nodes across the inputs | Space: O(h) for recursion, where h is the larger tree height.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript