Same Tree Easy 0 attempts
LeetCode ↗

Same Tree

Easy TreeBinary TreeDFS LeetCode

Given the roots of two binary trees, p and q, determine whether they're structurally identical with matching values at every corresponding position, returning true if so and false otherwise.

Both shape and values matter together — if one tree has a child where the other has none at that same position, the trees are different regardless of values elsewhere.

Input Format
Implement isSameTree(p, q). Inputs below show JavaScript function arguments; there is no stdin parsing. Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

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

Example 2

Input
p = [1,2]
q = [1,null,2]
Output
false
Constraints
  • 0 <= number of nodes <= 100
  • -10^4 <= Node.val <= 10^4
Test Cases (2)
Case 1
Args: [[1,2,3],[1,2,3]] Expected: true
Case 2
Args: [[1,2],[1,null,2]] Expected: false

Recursive

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) | Space: O(h)

Saved in this browser only. Private to you.

JavaScript