LeetCode 652. Find Duplicate Subtrees



Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

Example 1:

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2:

Input: root = [2,1,1]
Output: [[1]]

Example 3:

Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]


  • The number of the nodes in the tree will be in the range [1, 10^4]
  • -200 <= Node.val <= 200


We can use depth-first search to traverse the tree and build serialize strings of subtrees. Globally checking whether the serialize strings occur twice.

Python Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        self.counter = collections.Counter()
        self.results = []
        return self.results        
    def helper(self, root):
        if not root:
            return '#'
        serial = "{}, {}, {}".format(root.val, self.helper(root.left), self.helper(root.right))
        self.counter[serial] += 1
        if self.counter[serial] == 2:
        return serial
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *