-
Notifications
You must be signed in to change notification settings - Fork 43
/
find-duplicate-subtrees.py
259 lines (228 loc) · 6.92 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""
652. Find Duplicate Subtrees
Medium
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
Constraints:
The number of the nodes in the tree will be in the range [1, 10^4]
-200 <= Node.val <= 200
"""
# V0
# IDEA : DFS
# DEMO : defaultdict
# In [26]: import collections
# In [27]: m = collections.defaultdict(int)
#
# In [28]: m
# Out[28]: defaultdict(int, {})
#
# In [29]: m[0]
# Out[29]: 0
#
# In [30]: m
# Out[30]: defaultdict(int, {0: 0})
#
# In [31]: m[1]
# Out[31]: 0
#
# In [32]: m
# Out[32]: defaultdict(int, {0: 0, 1: 0})
#
# In [33]: m[1]=1
#
# In [34]: m
# Out[34]: defaultdict(int, {0: 0, 1: 1})
#
# In [35]: m[2] +=1
#
# In [36]: m
# Out[36]: defaultdict(int, {0: 0, 1: 1, 2: 1})
#
# Example 1 : root = [2,1,1]
# output :
# >>> m = defaultdict(<type 'int'>, {'2-1-#-#-1-#-#': 1, '1-#-#': 2})
#
# Example 2 : root = [2,2,2,3,null,3,null]
# output :
# >>> m = defaultdict(<type 'int'>, {'2-2-3-#-#-#-2-3-#-#-#': 1, '2-3-#-#-#': 2, '3-#-#': 2})
#
# Example 3 : root = [1,2,3,4,null,2,4,null,null,4]
# output :
# >>> m = defaultdict(<type 'int'>, {'4-#-#': 3, '1-2-4-#-#-#-3-2-4-#-#-#-4-#-#': 1, '2-4-#-#-#': 2, '3-2-4-#-#-#-4-#-#': 1})
#
#
import collections
class Solution(object):
def findDuplicateSubtrees(self, root):
res = []
m = collections.defaultdict(int)
self.dfs(root, m, res)
#print(">>> m = " + str(m))
return res
def dfs(self, root, m, res):
if not root:
return '#'
### Notice here
# every "self.dfs" means a "new start", so it will re-consider the duplicated sub-tree from current node
# i.e. : self.dfs(root.left, m, res) will re-consider the duplicated sub-tree left node
path = str(root.val) + '-' + self.dfs(root.left, m, res) + '-' + self.dfs(root.right, m, res)
### Notice here
# if m[path] == 1 means if there is already one element in the m
# -> so res append the path (if m[path] == 1)
# becasue it means "deplicate"
if m[path] == 1:
res.append(root)
m[path] += 1
return path
# V0'
import collections
class Solution(object):
def findDuplicateSubtrees(self, root):
self.res = []
self.m = collections.defaultdict(int)
self.dfs(root)
return self.res
def dfs(self, root):
if not root:
return ''
path = str(root.val) + '-' + self.dfs(root.left) + '-' + self.dfs(root.right)
if self.m[path] == 1:
self.res.append(root)
self.m[path] += 1
return path
# V0''
# IDEA : DFS
class Solution(object):
def findDuplicateSubtrees(self, root):
count = collections.Counter()
ans = []
def dfs(node):
if not node: return "#"
serial = "{}-{}-{}".format(node.val, dfs(node.left), dfs(node.right))
count[serial] += 1
if count[serial] == 2:
ans.append(node)
return serial
dfs(root)
return ans
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/81053453
# IDEA : DFS
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
res = []
m = collections.defaultdict(int)
self.helper(root, m, res)
return res
def helper(self, root, m, res):
if not root:
return '#'
path = str(root.val) + ',' + self.helper(root.left, m, res) + ',' + self.helper(root.right, m, res)
### Notice here
# if m[path] == 1 means if there is already one element in the m
# -> so res append the path (if m[path] == 1)
# becasue it means "deplicate"
if m[path] == 1:
res.append(root)
m[path] += 1
return path
### Test case : dev
# V1'
# IDEA : DFS
# https://leetcode.com/problems/find-duplicate-subtrees/solution/
class Solution(object):
def findDuplicateSubtrees(self, root):
count = collections.Counter()
ans = []
def collect(node):
if not node: return "#"
serial = "{},{},{}".format(node.val, collect(node.left), collect(node.right))
count[serial] += 1
if count[serial] == 2:
ans.append(node)
return serial
collect(root)
return ans
# V1''
# IDEA : Unique Identifier
# https://leetcode.com/problems/find-duplicate-subtrees/solution/
class Solution(object):
def findDuplicateSubtrees(self, root):
trees = collections.defaultdict()
trees.default_factory = trees.__len__
count = collections.Counter()
ans = []
def lookup(node):
if node:
uid = trees[node.val, lookup(node.left), lookup(node.right)]
count[uid] += 1
if count[uid] == 2:
ans.append(node)
return uid
lookup(root)
return ans
# V2
# 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