DEV Community

SalahElhossiny
SalahElhossiny

Posted on

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.

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

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

class Solution:
    def dfs(self, node, d):
        if not node:
            return 'N'
        l, r = self.dfs(node.left, d), self.dfs(node.right, d)
        path = str(node.val) + '-' + l + '-' + r

        if path in d:
            d[path] += 1
            if d[path] == 2:
                self.res.append(node)
        else:
            d[path] = 1
        return path

    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        self.res = []
        self.dfs(root, dict())
        return self.res




Enter fullscreen mode Exit fullscreen mode

Top comments (0)