05 August 2008
Given the
of a binary tree, return all duplicate subtrees.1
root
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:
1
2
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
1
2
Input: root = [2,1,1]
Output: [[1]]
Example 3:
1
2
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
Constraints:
1
[1, 10^4]
1
-200 <= Node.val <= 200
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.LinkedList;
class Solution {
public LinkedList<TreeNode> result = new LinkedList<>();
public HashMap<String,Integer> map = new HashMap<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
if(root == null){
return result;
}
serialize(root);
return result;
}
public String serialize(TreeNode root){
if(root == null){
return "null";
}
//序列化以当前节点为根节点的二叉树
String str = serialize(root.left) + ","+ root.val + ","+ serialize(root.right);
//使用一个HashMap来记录所有的子树的序列
map.put(str,map.getOrDefault(str,0)+1);
//当其value为2时,则表示出现了重复结构,将这个子树的根节点放入到结果当中。
if(map.get(str) == 2){
result.add(root);
}
return str;
}
}