Skip to content

Instantly share code, notes, and snippets.

@jeffchiucp
Created September 11, 2019 13:43
Show Gist options
  • Save jeffchiucp/48e8dbcd94a993d46ede67387ebc5712 to your computer and use it in GitHub Desktop.
Save jeffchiucp/48e8dbcd94a993d46ede67387ebc5712 to your computer and use it in GitHub Desktop.
findDuplicateSubtrees.py
def findDuplicateSubtrees(self, root):
def trv(root):
if not root: return "null"
struct = "%s,%s,%s" % (str(root.val), trv(root.left), trv(root.right))
nodes[struct].append(root)
return struct
nodes = collections.defaultdict(list)
trv(root)
return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1]
@jeffchiucp
Copy link
Author

Constraints

Time Complexity: O(N), where N is the number of nodes in the tree. We visit each node once.

Space Complexity: O(N). Every structure we use is using O(1)O(1) storage per node.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment