题意:
给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
两棵树重复是指它们具有相同的结构以及相同的结点值。
首先明确一下对子树的定义,这题里面的子树就是选定一个父节点然后一直到叶节点算一个子树,中间的一部分不能算是一个子树。
明白了这一点那么其实可以发现子树的数量是有限的,假设树节点有n个,那么子树最多就有n棵,注意如果左右字树为空就记为"null",不能什么都不记,否则会出现不同子树 但是是同样的序列。
一棵字树的序列可以由当前父节点的节点值加上左子树的序列和右子树的序列得到,得到这个序列可以用深搜的方式,然后用HashMap去判重即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<TreeNode>ans = new ArrayList<TreeNode>();
HashMap<String,Integer>map = new HashMap<String,Integer>();
public String dfs(TreeNode root)
{
if(root==null)
return "null";
String l = dfs(root.left);
String r= dfs(root.right);
String s = root.val+l+r;
int value = 0;
if(map.containsKey(s))
value = map.get(s);
if(value==1)
ans.add(root);
map.put(s,value+1);
return s;
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return ans;
}
}