Same Tree

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Same Tree

Approach

Recursively compare roots, and then both left and right child pairs.

Complexity Analysis

Time
O(n) where n is number of compared nodes
Space
O(h) where h is tree height

Pattern

Structural Comparison

Why It Works

Two trees are identical only if their roots match and all corresponding subtrees are identical.

Updated Feb 2026