Created
September 11, 2019 13:43
-
-
Save jeffchiucp/48e8dbcd94a993d46ede67387ebc5712 to your computer and use it in GitHub Desktop.
findDuplicateSubtrees.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.