1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution {
Map<String, Integer> map = new HashMap<>(); List<TreeNode> ans = new ArrayList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) { dfs(root); return ans; }
private String dfs(TreeNode node) { if (node == null) return " "; StringBuilder builder = new StringBuilder(); builder.append(node.val).append("_"); builder.append(dfs(node.left)).append(dfs(node.right)); String key = builder.toString(); map.merge(key, 1, Integer::sum); if (map.get(key) == 2) ans.add(node); return key; } }
|