Python, Simple - Using Postorder traversal


  • 0
    P
    class Solution:
         
        def findDuplicateSubtrees(self, root):
            """
            :type root: TreeNode
            :rtype: List[TreeNode]
            """
            freq = {}
            ans = []
            def postorder(root):
                if root is None: return "#"
                leftsub = postorder(root.left)
                rightsub = postorder(root.right)
                tree = leftsub + rightsub + str(root.val)
                if tree not in freq:
                    freq[tree] = 1
                elif freq[tree] == 1:
                    ans.append(root)
                    freq[tree] += 1
                return tree
            postorder(root)
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.