#652

Find Duplicate Subtrees

Medium
Hash TableTreeDepth-First SearchBinary TreeHash MapTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses serialization of subtrees and a hash map to track occurrences. This allows us to efficiently identify duplicates without unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a helper function to serialize each subtree into a string representation.
  2. 2Step 2: Use a hash map to count occurrences of each serialized subtree.
  3. 3Step 3: If a serialized subtree appears more than once, add its root to the result list.
solution.py24 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def findDuplicateSubtrees(self, root):
10        from collections import defaultdict
11        count = defaultdict(int)
12        result = []
13
14        def serialize(node):
15            if not node:
16                return '#'
17            serial = f'{node.val},{serialize(node.left)},{serialize(node.right)}'
18            count[serial] += 1
19            if count[serial] == 2:
20                result.append(node)
21            return serial
22
23        serialize(root)
24        return result

Complexity note: The time complexity is O(n) because we traverse each node once to serialize the tree, and the space complexity is O(n) due to the storage of serialized strings in the hash map.

  • 1Using serialization helps in uniquely identifying subtrees.
  • 2Hash maps are effective for counting occurrences efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.