Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Same Tree
Bookmark
Recursive DFS
Iterative BFS
Input
Same Trees
Different Structure
Different Values
Three Levels
Deep Mismatch
Custom
tree1
=
[1, 2, 3]
,
tree2
=
[1, 2, 3]
tree p
tree q
1
2
3
1
2
3
checks
isSameTree(p, q)
: compare pairs top-down
tree p
tree q
1
2
3
1
2
3
checks
isSameTree(p, q)
: compare pairs top-down
tree p
tree q
1
2
3
1
2
3
checks
1
2
2 = 2
, check left subtrees
tree p
tree q
1
2
3
1
2
3
∅
∅
checks
1
2
∅
∅ = ∅
: return true
tree p
tree q
1
2
3
1
2
3
∅
∅
checks
1
2
∅
∅
∅ = ∅
: return true
tree p
tree q
1
2
3
1
2
3
checks
1
2
∅
∅
subtree at 2 matches
: return true
tree p
tree q
1
2
3
1
2
3
checks
1
2
∅
∅
3
3 = 3
, check left subtrees
tree p
tree q
1
2
3
1
2
3
∅
∅
checks
1
2
∅
∅
3
∅
∅ = ∅
: return true
tree p
tree q
1
2
3
1
2
3
∅
∅
checks
1
2
∅
∅
3
∅
∅
∅ = ∅
: return true
tree p
tree q
1
2
3
1
2
3
checks
1
2
∅
∅
3
∅
∅
subtree at 3 matches
: return true
tree p
tree q
1
2
3
1
2
3
checks
1
2
∅
∅
3
∅
∅
return true
algo
master
.
io
Step:
Start: compare the two trees pair by pair
0 / 14
Input
Same Trees
Different Structure
Different Values
Three Levels
Deep Mismatch
Custom
tree1
=
[1, 2, 3]
,
tree2
=
[1, 2, 3]
0 / 14
algo
master
.
io
Step:
Start: compare the two trees pair by pair