Problem:
Given a binary tree, return all duplicate subtrees. 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 same node values.
Analysis:
- Store all the nodes into an ArrayList. And compare each pair
- serilize each node with the form:
series = (root.val, < encoder root.left >, < encoder root.right >)
In this way, each different node will have a unique series String - set ID number for each TreeNode
we can use map.computeIfAbsent
Some basic knowledge
map.computeIfAbsent:
Object key = map.get(“key”);
if (key == null) {
key = new Object();
map.put(“key”, key);
}
// the above code is the same as:
Object key2 = map.computeIfAbsent(“key”, k -> new Object());
public class Solution1 {
// method 2
public List<TreeNode> findDuplicateSubtrees(TreeNode root){
HashMap<String, Integer> counter = new HashMap<>();
List<TreeNode> nodes = new ArrayList<TreeNode>();
serilization(counter, nodes, root);
return nodes;
}
public String serilization(HashMap<String, Integer> counter, List<TreeNode> nodes, TreeNode root){
if (root == null) return "";
String series = "(" + root.val + "," + serilization(counter, nodes, root.left) + "," + serilization(counter, nodes, root.right) + ")";
counter.put(series, counter.getOrDefault(series, 0) + 1);
if (counter.get(series) == 2) {
nodes.add(root);
}
return series;
}
// method 3
int t = 1;
public List<TreeNode> findDuplicateSubtrees1(TreeNode root){
HashMap<String, Integer> IDs = new HashMap<>();
HashMap<Integer, Integer> counter = new HashMap<>();
List<TreeNode> res = new ArrayList<>();
setID(IDs, counter, res, root);
return res;
}
public int setID(HashMap<String, Integer> IDs, HashMap<Integer, Integer> counter, List<TreeNode> res, TreeNode root){
if (root == null) return 0;
int leftNum = setID(IDs, counter, res, root.left);
int rightNum = setID(IDs, counter, res, root.right);
String nodeExpre = "(" + root.val + "," + leftNum + "," + rightNum + ")";
int ID = IDs.computeIfAbsent(nodeExpre, x -> t++);
counter.put(ID, counter.getOrDefault(ID, 0)+1);
if (counter.get(ID) == 2) {
res.add(root);
}
return ID;
}
}
本文介绍了一种用于查找二叉树中所有重复子树的方法。通过序列化节点并使用哈希映射来跟踪每个子树出现的次数,该算法能够有效地识别出所有重复的子树结构。提供两种实现方式:一种直接比较序列化的字符串;另一种则为每个唯一子树分配ID进行跟踪。
8万+

被折叠的 条评论
为什么被折叠?



