652. Find Duplicate Subtrees

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
       /
      4
The following are two duplicate subtrees:
      2
     /
    4
and
    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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值