forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
find-duplicate-subtrees.py
51 lines (44 loc) · 1.47 KB
/
find-duplicate-subtrees.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def getid(root, lookup, trees):
if root:
node_id = lookup[root.val, \
getid(root.left, lookup, trees), \
getid(root.right, lookup, trees)]
trees[node_id].append(root)
return node_id
trees = collections.defaultdict(list)
lookup = collections.defaultdict()
lookup.default_factory = lookup.__len__
getid(root, lookup, trees)
return [roots[0] for roots in trees.values() if len(roots) > 1]
# Time: O(n * h)
# Space: O(n * h)
class Solution2(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def postOrderTraversal(node, lookup, result):
if not node:
return ""
s = "(" + postOrderTraversal(node.left, lookup, result) + \
str(node.val) + \
postOrderTraversal(node.right, lookup, result) + \
")"
if lookup[s] == 1:
result.append(node)
lookup[s] += 1
return s
lookup = collections.defaultdict(int)
result = []
postOrderTraversal(root, lookup, result)
return result