Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Find Duplicate Subtrees
Bookmark
Brute Force
Serialization
ID-Based
Input
Example 1
Example 2
Example 3
Custom
tree
=
[1, 2, 3, 4, null, 2, 4, null, null, 4]
1
2
3
4
2
4
4
allNodes
result
collect every node, then compare each subtree with every earlier one
1
2
3
4
2
4
4
allNodes
result
collect every node, then compare each subtree with every earlier one
1
2
3
4
2
4
4
allNodes
1
2
4
3
2
4
result
allNodes +=
4
1
2
3
4
2
4
4
earlierMatches
0
allNodes
1
2
4
i
3
2
4
4
result
i = 2:
subtree at 4
, earlierMatches = 0
1
2
3
4
2
4
4
earlierMatches
0
allNodes
1
j
2
4
3
i
2
4
4
isSame
a
3
b
1
≠
result
isSame(
3
,
1
): values differ, false
1
2
3
4
2
4
4
earlierMatches
0
allNodes
1
2
4
3
2
i
4
4
result
i = 4:
subtree at 2
, earlierMatches = 0
1
2
3
4
2
4
4
earlierMatches
1
allNodes
1
2
4
3
j
2
i
4
4
isSame
a
2
b
3
≠
result
isSame(
2
,
3
): values differ, false
1
2
3
4
2
4
4
earlierMatches
0
allNodes
1
2
j
4
3
2
4
i
4
result
2
subtree at 2 differs
, earlierMatches = 0
1
2
3
4
2
4
4
earlierMatches
1
allNodes
1
2
4
3
2
4
i
4
result
2
4
earlierMatches == 1: result +=
4
1
2
3
4
2
4
4
earlierMatches
1
allNodes
1
2
4
3
j
2
4
4
i
isSame
a
4
b
3
≠
result
2
4
isSame(
4
,
3
): values differ, false
1
2
3
4
2
4
4
earlierMatches
-
allNodes
1
2
4
3
2
4
4
result
2
4
return [2, 4]
algo
master
.
io
Step:
Start: collect every node, then compare each subtree with every earlier one using isSame
0 / 66
Input
Example 1
Example 2
Example 3
Custom
tree
=
[1, 2, 3, 4, null, 2, 4, null, null, 4]
0 / 66
algo
master
.
io
Step:
Start: collect every node, then compare each subtree with every earlier one using isSame