LeetCode ยท #100

Same Tree Solution

Given two binary trees, check if they are structurally identical and have the same node values.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #100

๐Ÿ—๏ธ

Pattern

Recursion โ€” parallel traversal

Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two trees are the same if they are structurally identical and the nodes have the same values.

Example
Input: p = [1,2,3], q = [1,2,3] Output: true
Constraints
โ€ข 0 โ‰ค number of nodes โ‰ค 100 โ€ข -10โด โ‰ค Node.val โ‰ค 10โด
02
Section Two ยท Approach 1

Serialize & Compare โ€” O(n)

Serialize both trees to strings (preorder with null markers) and compare strings. Works but allocates O(n) string space unnecessarily.

03
Section Three ยท Approach 2

Recursive Comparison โ€” O(n)

Compare nodes in parallel: (1) both null โ†’ true, (2) one null โ†’ false, (3) values differ โ†’ false, (4) recurse on left and right children.

๐Ÿ’ก Mental model: Two people walk through two houses simultaneously. At each room they check: "Same room exists? Same furniture?" If any mismatch, stop. If both reach dead ends at the same time โ†’ identical layout.
๐ŸŽฏ Building block: isSameTree is used as a helper in LC 572 (Subtree of Another Tree) โ€” check it at every node of the main tree.
04
Section Four ยท Trace

Visual Walkthrough

Parallel comparison โ€” p=[1,2,3] vs q=[1,2,3]
TREE p 1 2 3 == TREE q 1 2 3 PARALLEL COMPARISON โ‘  Roots: p.val=1 == q.val=1 โ†’ โœ“ match. Recurse left & right. โ‘ก Left: p.left=2 == q.left=2 โ†’ โœ“ match. Both children null โ†’ true. โ‘ข Right: p.right=3 == q.right=3 โ†’ โœ“ match. Both children null โ†’ true. Answer: true โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Recursive
class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null) return false; if (p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
Python โ€” Recursive
class Solution: def isSameTree(self, p, q) -> bool: if not p and not q: return True if not p or not q: return False return (p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right))
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
RecursiveO(n)O(h) โ€” stack depth
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Both emptynull, nullSame โ†’ true.
One empty[1], nullDifferent structure โ†’ false.
Same structure, different values[1,2], [1,3]Values mismatch at p.left vs q.left โ†’ false.

โ† Back to Trees problems