Skip to content

Commit fc265ce

Browse files
committed
find duplicate subtrees
1 parent 1cd1709 commit fc265ce

File tree

3 files changed

+100
-35
lines changed

3 files changed

+100
-35
lines changed

.idea/workspace.xml

Lines changed: 36 additions & 35 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,3 +385,4 @@ codes may not be optimized
385385
1. [Validate UTF-8](https://leetcode.com/problems/utf-8-validation/description/)
386386
1. [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/)
387387
1. [Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/description/)
388+
1. [Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/description/)
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.github.chen0040.leetcode.day18.medium;
2+
3+
4+
import java.util.*;
5+
6+
7+
/**
8+
* Created by xschen on 13/8/2017.
9+
*
10+
* link: https://leetcode.com/problems/find-duplicate-subtrees/description/
11+
*/
12+
public class FindDuplicateSubtrees {
13+
public class TreeNode {
14+
int val;
15+
TreeNode left;
16+
TreeNode right;
17+
TreeNode(int x) { val = x; }
18+
}
19+
20+
public class Solution {
21+
Map<String, TreeNode> repeated;
22+
Set<String> signatures;
23+
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
24+
repeated = new HashMap<String, TreeNode>();
25+
signatures = new HashSet<String>();
26+
preorder(root);
27+
return new ArrayList<TreeNode>(repeated.values());
28+
}
29+
30+
private String preorder(TreeNode x) {
31+
if(x == null) {
32+
return "#";
33+
}
34+
35+
String prefix = "";
36+
if(x.left == null && x.right == null) {
37+
prefix = "" + x.val;
38+
} else {
39+
prefix = append(prefix, "" + x.val);
40+
prefix = append(prefix, preorder(x.left));
41+
prefix = append(prefix, preorder(x.right));
42+
}
43+
44+
//System.out.println(prefix);
45+
if(signatures.contains(prefix)) {
46+
repeated.put(prefix, x);
47+
}
48+
signatures.add(prefix);
49+
50+
return prefix;
51+
}
52+
53+
private String append(String prefix, String val) {
54+
if(prefix.equals("")) {
55+
prefix = val;
56+
} else {
57+
prefix = prefix + "," + val;
58+
}
59+
60+
return prefix;
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)