Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of anyoneof them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees' root in the form of a list.
这题呢,一开始就只想到暴力解。利用100 Same Tree (L469)来判断是否相同,然后遍历全树。其实呢,也是个n方的解法呀,不知为毛没过大数据。后来看了答案才发现应该用L245 Subtree (572)的解法。因为preorder+null可以唯一确定一棵树。所以把这个string作为key,放到hashmap里。也是O(n^2),因为每次建立这个key都得O(n),我们要遍历全树。这里处理方法有点想不到,以前一直觉得hm里存的东西要返回。这里结果是另外存的,hashmap只是用来数数的。