-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtree_of_another_tree.py
332 lines (281 loc) · 12 KB
/
subtree_of_another_tree.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python3
# Subtree of Another Tree
#
# https://leetcode.com/problems/subtree-of-another-tree
#
# Given the roots of two binary trees root and subRoot, return true if there is
# a subtree of root with the same structure and node values of subRoot and false
# otherwise.
# A subtree of a binary tree tree is a tree that consists of a node in tree and
# all of this node's descendants. The tree tree could also be considered as a
# subtree of itself.
from typing import List, Optional
from binary_tree import TreeNode
def test():
"""
Run `pytest <this-file>`.
"""
def test_algo(algo):
assert (
algo(
root=TreeNode(
3,
left=TreeNode(4, left=TreeNode(1), right=TreeNode(2)),
right=TreeNode(5),
),
subRoot=TreeNode(4, left=TreeNode(1), right=TreeNode(2)),
)
== True
)
assert (
algo(
root=TreeNode(
3,
left=TreeNode(
4, left=TreeNode(1), right=TreeNode(2, left=TreeNode(0))
),
right=TreeNode(5),
),
subRoot=TreeNode(4, left=TreeNode(1), right=TreeNode(2)),
)
== False
)
assert (
algo(
root=TreeNode(
1,
left=TreeNode(2),
right=TreeNode(3),
),
subRoot=TreeNode(
1,
left=TreeNode(2),
),
)
== False
)
assert (
algo(
root=TreeNode(
12,
),
subRoot=TreeNode(
2,
),
)
== False
)
# Test all different algorithms/implementations
solution = Solution()
for algo in [
solution.brute_force,
solution.hash_tree,
solution.preorder_traversal,
solution.preorder_traversal_regex,
solution.preorder_traversal_substring_search,
]:
test_algo(algo)
class Solution:
def brute_force(
self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) -> bool:
"""
Approach: Brute-force.
Idea: For every node in root, check if the subtree rooted at that node is equal to the given subtree.
Time: O(n * m): Given a root with n nodes and a subtree with m nodes, for each node in the root, checking equality with the given subtree is O(m).
Space: O(1): No additional memory is used.
Leetcode: 103 ms runtime, 16.74 MB memory
"""
def same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
match (p, q):
case (None, None):
return True
case (None, _) | (_, None):
return False
case (some_p, some_q):
return (
some_p.val == some_q.val
and same_tree(some_p.left, some_q.left)
and same_tree(some_p.right, some_q.right)
)
case _:
raise Exception("unreachable")
def same_subtree(
root: Optional[TreeNode], sub_root: Optional[TreeNode]
) -> bool:
match (root, sub_root):
case (None, _):
return same_tree(root, sub_root)
case (some_root, _):
return (
same_tree(some_root, sub_root)
or same_subtree(some_root.left, sub_root)
or same_subtree(some_root.right, sub_root)
)
case _:
raise Exception("unreachable")
return same_subtree(root, subRoot)
def hash_tree(
self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) -> bool:
"""
Approach: Hash tree, or Merkle tree.
Idea: For every node in root, check if the subtree rooted at that node is equal to the given subtree. However, make checking equality of trees efficient by assigning every node in each tree a hash value, which is generated from a node's value plus the hashes of its children.
Time: O(n + m): Given a root with n nodes and a subtree with m nodes, first we traverse all nodes in each tree to set the hash values (O(n + m)), and then checking equality of trees is O(1), so we need to check if subtrees rooted at any node in root are equal to the given subtree (O(1) each).
Space: O(n + m): Each node in each tree gets an additional hash value/attribute.
Leetcode: 70 ms runtime, 20.64 MB memory
"""
from hashlib import sha256
def hash(x: str):
return sha256(x.encode()).hexdigest()
def add_hash_to_nodes(node: Optional[TreeNode]) -> str:
if node is None:
return "#"
else:
node.hash = hash(
add_hash_to_nodes(node.left)
+ str(node.val)
+ add_hash_to_nodes(node.right)
)
return node.hash
add_hash_to_nodes(root)
add_hash_to_nodes(subRoot)
def same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
match (p, q):
case (None, None):
return True
case (None, _) | (_, None):
return False
case (some_p, some_q):
return some_p.hash == some_q.hash
case _:
raise Exception("unreachable")
def same_subtree(
root: Optional[TreeNode], sub_root: Optional[TreeNode]
) -> bool:
match (root, sub_root):
case (None, _):
return same_tree(root, sub_root)
case (some_root, _):
return (
same_tree(some_root, sub_root)
or same_subtree(some_root.left, sub_root)
or same_subtree(some_root.right, sub_root)
)
case _:
raise Exception("unreachable")
return same_subtree(root, subRoot)
def preorder_traversal(
self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) -> bool:
"""
Approach: Serialize tree using pre-order traversal.
Idea: Serialize both tree using pre-order traversal, and then check if the subroot list is a sublist of the root list.
Time: O(n*m): Given the root has n nodes and the subroot has m nodes, the preorder traversals take (O(n+m)), and a naive sublist matching (with a sliding window) takes O(n*m).
Space: O(n+m): The serialized trees have sizes n and m.
Leetcode: 74 ms runtime, 17.26 MB memory
"""
from collections import deque
import itertools
def preorder_traversal(start: Optional[TreeNode], visit):
def rec(node: Optional[TreeNode]):
if node is not None:
visit(node)
rec(node.left)
rec(node.right)
else:
visit(None)
rec(start)
root_order = []
sub_root_order = []
def visit_root(node: Optional[TreeNode]):
root_order.append(node.val if node is not None else "#")
def visit_sub_root(node: Optional[TreeNode]):
sub_root_order.append(node.val if node is not None else "#")
preorder_traversal(root, visit_root)
preorder_traversal(subRoot, visit_sub_root)
def sliding_window(iterable, n):
it = iter(iterable)
window = deque(itertools.islice(it, n - 1), maxlen=n)
for x in it:
window.append(x)
yield tuple(window)
def list_contains_sublist(list: List[int], sublist: List[int]) -> bool:
return any(
window == tuple(sublist)
for window in sliding_window(list, len(sublist))
)
# Subroot is a subtree of root if its pre-order traversal list is
# contained in root's pre-order traversal list.
return list_contains_sublist(root_order, sub_root_order)
def preorder_traversal_regex(
self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) -> bool:
"""
Approach: Serialize tree using pre-order traversal, regex search.
Idea: Serialize both tree using pre-order traversal, and then check if the subroot list is a sublist of the root list.
Time: O(n*m): Given the root has n nodes and the subroot has m nodes, the preorder traversals take (O(n+m)), converting each to strings (O(n+m)), and check if subroot is sublist with regex (assumed O(n*m)).
Space: O(n+m): The serialized trees have sizes n and m.
Leetcode: 87 ms runtime, 17.76 MB memory
"""
import re
def preorder_traversal(start: Optional[TreeNode], visit):
def rec(node: Optional[TreeNode]):
if node is not None:
visit(node)
rec(node.left)
rec(node.right)
else:
visit(None)
rec(start)
root_order = []
sub_root_order = []
def visit_root(node: Optional[TreeNode]):
root_order.append(node.val if node is not None else "#")
def visit_sub_root(node: Optional[TreeNode]):
sub_root_order.append(node.val if node is not None else "#")
preorder_traversal(root, visit_root)
preorder_traversal(subRoot, visit_sub_root)
root_order_str = ",".join(map(str, root_order))
sub_root_order_str = ",".join(map(str, sub_root_order))
# Subroot is a subtree of root if its pre-order traversal list is
# contained in root's pre-order traversal list.
return (
re.search(rf"(^|,){sub_root_order_str}($|,)", root_order_str)
is not None
)
# return sub_root_order_str in root_order_str
def preorder_traversal_substring_search(
self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) -> bool:
"""
Approach: Serialize tree using pre-order traversal, substring search.
Idea: Serialize both tree using pre-order traversal, and then check if the subroot list is a sublist of the root list.
Time: O(n+m): Given the root has n nodes and the subroot has m nodes, the preorder traversals take (O(n+m)), converting each to strings (O(n+m)), and check if subroot is substring with "in" (assumed O(n+m), similar to KMP).
Space: O(n+m): The serialized trees have sizes n and m.
Leetcode: 62 ms runtime, 17.36 MB memory
"""
def preorder_traversal(start: Optional[TreeNode], visit):
def rec(node: Optional[TreeNode]):
if node is not None:
visit(node)
rec(node.left)
rec(node.right)
else:
visit(None)
rec(start)
root_order = []
sub_root_order = []
def visit_root(node: Optional[TreeNode]):
root_order.extend(["^", node.val] if node is not None else ["#"])
def visit_sub_root(node: Optional[TreeNode]):
sub_root_order.extend(
["^", node.val] if node is not None else ["#"]
)
preorder_traversal(root, visit_root)
preorder_traversal(subRoot, visit_sub_root)
root_order_str = ",".join(map(str, root_order))
sub_root_order_str = ",".join(map(str, sub_root_order))
# Subroot is a subtree of root if its pre-order traversal list is
# contained in root's pre-order traversal list.
return sub_root_order_str in root_order_str