LeetCode 652: Find Duplicate Subtrees (Python recursion memorization)

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]]:
        result = []       
        hashMap = {} #key: serilization strings for trees, value: numbers of appearance of strings 
        #Recursion + Memorization
        #Use recursion to serilize the tree for each node
        #Store the serilizations for trees in hash map
        def recursion(node, path):
            if node is None:
                return '#'
            #Serilization, preorder traversal
            path += ','.join([str(node.val), recursion(node.left, path), recursion(node.right, path)])
            print(path)
            if path in hashMap:
                hashMap[path] += 1
                if hashMap[path] == 2:
                    result.append(node)
            else:
                hashMap[path] = 1
                           
            return path
        
        recursion(root, '')
         
        return result

        #Time Complexity: O(n)
        #Space complexity: O(n)

 

Time Complexity: O(n)

Space Complexity: O(n)


Feeling tired? You can also try our free online no-installation required casual games: Here Please consider to follow my youtube channel to support me: