|
| 1 | +/** |
| 2 | +* Given a binary tree, return all duplicate subtrees. For each kind of |
| 3 | +* duplicate subtrees, you only need to return the root node of any one of them. |
| 4 | +* |
| 5 | +* Two trees are duplicate if they have the same structure with same node values. |
| 6 | +* |
| 7 | +* Example 1: |
| 8 | +* |
| 9 | +* 1 |
| 10 | +* / \ |
| 11 | +* 2 3 |
| 12 | +* / / \ |
| 13 | +* 4 2 4 |
| 14 | +* / |
| 15 | +* 4 |
| 16 | +* |
| 17 | +* The following are two duplicate subtrees: |
| 18 | +* |
| 19 | +* 2 |
| 20 | +* / |
| 21 | +* 4 |
| 22 | +* |
| 23 | +* and |
| 24 | +* |
| 25 | +* 4 |
| 26 | +* |
| 27 | +* Therefore, you need to return above trees' root in the form of a list. |
| 28 | +*/ |
| 29 | + |
| 30 | +/** |
| 31 | +* Definition for a binary tree node. |
| 32 | +* public class TreeNode { |
| 33 | +* int val; |
| 34 | +* TreeNode left; |
| 35 | +* TreeNode right; |
| 36 | +* TreeNode(int x) { val = x; } |
| 37 | +* } |
| 38 | +*/ |
| 39 | + |
| 40 | +public class FindDuplicateSubtrees652 { |
| 41 | +public List<TreeNode> findDuplicateSubtrees(TreeNode root) { |
| 42 | +List<TreeNode> res = new ArrayList<>(); |
| 43 | +if (root == null) return res; |
| 44 | +Map<String, Boolean> visited = new HashMap<>(); |
| 45 | +findDuplicates(root, visited, res); |
| 46 | +return res; |
| 47 | +} |
| 48 | + |
| 49 | +private String findDuplicates(TreeNode root, Map<String, Boolean> visited, List<TreeNode> res) { |
| 50 | +if (root == null) { |
| 51 | +return "N"; |
| 52 | +} |
| 53 | +String self = Integer.toString(root.val); |
| 54 | +String left = findDuplicates(root.left, visited, res); |
| 55 | +String right = findDuplicates(root.right, visited, res); |
| 56 | +String curr = self + "-" + left + "-" + right; |
| 57 | +if (!visited.containsKey(curr)) { |
| 58 | +visited.put(curr, false); |
| 59 | +} else { |
| 60 | +if (!visited.get(curr)) { |
| 61 | +res.add(root); |
| 62 | +visited.put(curr, true); |
| 63 | +} |
| 64 | +} |
| 65 | +return curr; |
| 66 | +} |
| 67 | + |
| 68 | +} |
0 commit comments