FrontendInterviews.dev

Loading problem…

92. Same Tree - Tree Comparison

Easy•
Acceptance: 85.71%
•
🔓3/3 Pro unlocks today

You're building a form validation or data comparison feature that needs to verify whether two nested tree-like structures are identical.

Given the roots of two binary trees p and q, return true if they are the same.

Two binary trees are considered the same if:

  • They are structurally identical (nulls appear in the same positions), and
  • Every corresponding node has the same value.

Requirements

1. Basic Functionality

  • Compare structure (left/right child positions must match)
  • Compare values at corresponding nodes
  • Handle empty trees (both null)

Example Usage

isSameTree([1,2,3], [1,2,3]);       // true
isSameTree([1,2],   [1,null,2]);    // false
isSameTree([1,2,1], [1,1,2]);       // false

Real-World Context

  • Form state comparison: check if nested form values changed
  • Tree validation: validate nested schemas or configs
  • Data synchronization: decide if two versions are identical
  • UI state diffing: compare hierarchical UI state snapshots

Constraints

  • 0 <= number of nodes <= 100
  • -10^4 <= Node.val <= 10^4