1、题目描述
https://leetcode-cn.com/problems/find-duplicate-subtrees/
2、解法
class Solution {
LinkedList<TreeNode> res = new LinkedList<TreeNode>();//存储结果
HashMap<String,Integer> memo = new HashMap<>();//记录所有子树出现的次数
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverN(root);
return res;
}
//返回的是字符串
public String traverN(TreeNode root){
//第一步,将问题归结为根节点要做什么,我这颗子树长啥样,其他子树长啥样
//我这个子树长啥样——使用拼接字符串的方式来序列化二叉树
if(root==null) return "#";//#代表null
String left = traverN(root.left);
String right = traverN(root.right);
String subTree = left+","+right+","+root.val;//一块子树的样子——
//子树长啥样——使用某种数据结构记录下来_使用HashMap,每个重复的样子我们只记录一次
//getOrDefault() 方法获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。
int time = memo.getOrDefault(subTree,0);//计算哈希码要时间O(n)
// 多次重复也只会被加入结果集一次
if (time == 1) {
res.add(root);
}
// 给子树对应的出现次数加一
memo.put(subTree, time + 1);
return subTree;
}
}
效率上,主要是字符串的拼接、对应哈希码的计算O(n),n个节点计算。
故时间复杂度O(n2),空间复杂度O(n2)。
必须优化
官方题解解法二里面:
class Solution {
int t;
Map<String, Integer> trees;
Map<Integer, Integer> count;
List<TreeNode> ans;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
t = 1;
trees = new HashMap();
count = new HashMap();
ans = new ArrayList();
lookup(root);
return ans;
}
public int lookup(TreeNode node) {
if (node == null) return 0;
String serial = node.val + "," + lookup(node.left) + "," + lookup(node.right);
int uid = trees.computeIfAbsent(serial, x-> t++);
//利用计算得到的id,来标识
count.put(uid, count.getOrDefault(uid, 0) + 1);
if (count.get(uid) == 2)
ans.add(node);
return uid;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/find-duplicate-subtrees/solution/xun-zhao-zhong-fu-de-zi-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
我们先来了解一下该函数——Java HashMap computeIfAbsent() 方法
-
computeIfAbsent() 方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hasMap 中。
-
computeIfAbsent() 方法的语法为:
hashmap.computeIfAbsent(K key, Function remappingFunction)
参数说明:
key - 键
remappingFunction - 重新映射函数,用于重新计算值
返回值
如果 key 对应的 value 不存在,则使用获取 remappingFunction 重新计算后的值,并保存为该 key 的 value,否则返回 value。
尝试去提交一手:
从均值复杂度的角度,应该是如同分析的那样了。