Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Input & Output

Example 1 — Identical Trees
$ Input: p = [1,2,3], q = [1,2,3]
Output: true
💡 Note: Both trees have the same structure: root 1 with left child 2 and right child 3. All corresponding nodes have identical values.
Example 2 — Different Structure
$ Input: p = [1,2], q = [1,null,2]
Output: false
💡 Note: Tree p has node 2 as left child of root 1, while tree q has node 2 as right child of root 1. Different structure makes them not identical.
Example 3 — Different Values
$ Input: p = [1,2,1], q = [1,1,2]
Output: false
💡 Note: Same structure but different values: p has left=2, right=1 while q has left=1, right=2. Values don't match at corresponding positions.

Constraints

  • The number of nodes in both trees is in the range [0, 100]
  • -104 ≤ Node.val ≤ 104

Visualization

Tap to expand
Same Tree - DFS Approach INPUT Tree P 1 2 3 Tree Q 1 2 3 p = [1,2,3] q = [1,2,3] ALGORITHM STEPS 1 Base Case Check Both null? Return true One null? Return false 2 Compare Values p.val == q.val? 1==1 OK, 2==2 OK, 3==3 OK 3 Recurse Left DFS(p.left, q.left) Compare left subtrees 4 Recurse Right DFS(p.right, q.right) Compare right subtrees DFS Order: 1 --> 2 --> 3 OK FINAL RESULT Trees Match! 1 2 3 OK OK OK Output: true Structurally identical with same values SAME TREE! Key Insight: DFS recursively compares corresponding nodes in both trees. At each step, we check: (1) Both nodes null --> equal, (2) One null --> not equal, (3) Values match --> recurse on children. Time: O(n) where n = min nodes | Space: O(h) where h = tree height (recursion stack) TutorialsPoint - Same Tree | DFS Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 15
312.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen