Skip to content

Commit 597e474

Browse files
authored
Update find-duplicate-subtrees.py
1 parent bc78022 commit 597e474

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

Python/find-duplicate-subtrees.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
# Time: O(n * h)
2-
# Space: O(n * h)
1+
# Time: O(n)
2+
# Space: O(n)
33

44
# Given a binary tree, return all duplicate subtrees.
55
# For each kind of duplicate subtrees, you only need to return the root node of any one of them.
@@ -30,6 +30,26 @@
3030
# self.right = None
3131

3232
class Solution(object):
33+
def findDuplicateSubtrees(self, root):
34+
"""
35+
:type root: TreeNode
36+
:rtype: List[TreeNode]
37+
"""
38+
def getid(root, result):
39+
if root:
40+
id = lookup[root.val, getid(root.left, result), getid(root.right, result)]
41+
result[id].append(root)
42+
return id
43+
result = collections.defaultdict(list)
44+
lookup = collections.defaultdict()
45+
lookup.default_factory = lookup.__len__
46+
getid(root, result)
47+
return [roots[0] for roots in result.values() if len(roots) > 1]
48+
49+
50+
# Time: O(n * h)
51+
# Space: O(n * h)
52+
class Solution2(object):
3353
def findDuplicateSubtrees(self, root):
3454
"""
3555
:type root: TreeNode

0 commit comments

Comments
 (0)