652.寻找重复的子树
/**
* 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;
* }
* }
*/
class Solution {
Map<String,TreeNode> treeMap = new HashMap<>();
Set<String> keySet = new HashSet<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
visitTreeNode(root);
return new ArrayList<>(treeMap.values());
}
private String visitTreeNode(TreeNode node){
if(node == null){
return "";
}
//将节点的value和它的左子树和右子树节点拼接起来作为key
String treeNodeKey = node.val+"(" + visitTreeNode(node.left)+","+visitTreeNode(node.right)+")";
if(!keySet.add(treeNodeKey)){
treeMap.put(treeNodeKey,node);
}
return treeNodeKey;
}
}