- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path652.py
More file actions
Latest commit
36 lines (28 loc) · 981 Bytes
/
Copy path652.py
File metadata and controls
36 lines (28 loc) · 981 Bytes
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
fromcollectionsimportdefaultdict
fromtypingimportList
# Name: Find Duplicate Subtrees
# Link: https://leetcode.com/problems/find-duplicate-subtrees/submissions/
# Method: Solving tidbit
# Time: O(n^2)
# Space: O(n^2)
# Difficulty: Medium
classTreeNode:
def__init__(self, val=0, left=None, right=None):
self.val=val
self.left=left
self.right=right
classSolution:
deffindDuplicateSubtrees(self, root: TreeNode) ->List[TreeNode]:
node_repr=defaultdict(list)
defstringify_tree(node: TreeNode):
ifnotnode:
return"null"
left_res=stringify_tree(node.left)
right_res=stringify_tree(node.right)
res=f"{node.val},{left_res},{right_res}"
node_repr[res].append(node)
returnres
stringify_tree(root)
return [
tree_roots[0] fortree_rootsinnode_repr.values() iflen(tree_roots) >1
]