-
Notifications
You must be signed in to change notification settings - Fork 5
/
0652.py
27 lines (25 loc) · 851 Bytes
/
0652.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
import collections
res = []
counter = collections.Counter()
def traverse(root):
if not root:
return '#'
# 后序遍历
left = traverse(root.left)
right = traverse(root.right)
chain = left + ',' + right + ',' + str(root.val)
counter[chain] += 1
# 统计出现两次即是重复子树,加入res
if counter[chain] == 2:
res.append(root)
return chain
traverse(root)
return res