Same Tree - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

We check whether two binary trees p and q are the same by recursively comparing corresponding nodes in a synchronized DFS. The trees are the same iff they are structurally identical and every pair of corresponding nodes has the same value.

  • Base cases
    • ✅ If p === null and q === null → match at this position (return true).
    • ❌ If exactly one of p or q is null → structural mismatch (return false).
    • ❌ If both exist but p.val !== q.val → value mismatch (return false).
  • Recursive step
    After confirming the current pair matches in value, the trees are the same at this position iff both left and right subtrees are the same. Return:
    isSame(p.left, q.left) && isSame(p.right, q.right).
  • Short-circuiting
    On the first structural or value mismatch we return false immediately, avoiding unnecessary work.

Time Complexity

O(min(m, n)) — where m and n are the number of nodes in trees p and q. In the worst case, we do not hit a base case until fully traversing the smaller (or identical) tree.

Space Complexity

O(min(m, n)) — recursion stack depth is proportional to the height of the smaller (or identical) tree, which can reach the total node count in the case of a skewed structure.

Visucodize editorial solution titled JS Solution for LeetCode's Same Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/same-tree.