Find Duplicate Subtrees
1
/ \
2 3
/ / \
4 2 4
/
4 2
/
4 4class Solution {
private final List<TreeNode> duplicates = new ArrayList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
// a node in a binary tree is: node, node.left and node.right
// we need to iterate through the nodes and build key for each node, then as we are building the keys and a hash map, we check for duplicate keys, if duplicate key is found, we add that node into list
// 1 -> 2 ->null,null
// 1 -> 2 ->null,null
find(root);
return duplicates;
}
private Map<String, Integer> keys = new HashMap<>();
public String find(TreeNode node) {
if (node == null) return "-";
String key = String.valueOf(node.val) + find(node.left) + find(node.right);
System.out.println(key);
if (keys.containsKey(key) && keys.get(key) == 0) {
System.out.println("adding...");
duplicates.add(node);
keys.put(key, 1);
} else {
if (!keys.containsKey(key)) {
keys.put(key, 0);
}
}
return key;
}
}Last updated