Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1 / \ 2 3 / / \ 4 2 4 / 4The following are two duplicate subtrees:
2 / 4and
4
Therefore, you need to return above trees' root in the form of a list.
思路:刚开始遍历保存所有节点到List,然后对List中的两两判断是不是一样的树,TLE
答案是序列化为String放到HashTable中
之前一直没搞清楚:序列化可以唯一标识一棵树。只是前序遍历结果并不能
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Solution {
Set<String> s = new HashSet<String>();
Set<String> ss = new HashSet<String>();
List<TreeNode> ret = new ArrayList<TreeNode>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
t(root, new StringBuilder());
// for(TreeNode k : map.keySet())
// System.out.println(k.val + " " + map.get(k));
return ret;
}
private String t(TreeNode root, StringBuilder sb) {
if(root == null) return "null&";
// if(root.left==null && root.right==null) {
// map.put(root, root.val+"");
// return root.val+"";
// }
sb.append(root.val + "&");
sb.append(t(root.left, new StringBuilder()));
sb.append(t(root.right, new StringBuilder()));
String fi = sb.toString();
if(s.contains(fi)) {
if(!ss.contains(fi)) {
ret.add(root);
ss.add(fi);
}
} else {
s.add(fi);
}
return fi;
}
}
class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def trav(root):
if not root: return 'null'
hashstring = '%s,%s,%s' % (str(root.val), trav(root.left), trav(root.right)) # inorder
nodes[hashstring].append(root)
return hashstring
nodes = collections.defaultdict(list)
trav(root)
return [nodes[hashstring][0] for hashstring in nodes if len(nodes[hashstring])>1]