leetcode.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.

题意:

在一个二叉树中,寻找相同的子树,相同子树要有相同的结构和相同的节点的值。

思路:

最开始的思路是用纯粹的递归判断每个子树,但是这种解法会超时。

discuss中的高票答案提供的思路是将每一个节点的左右子树的value序列化,存储在hashmap中,这样就是判断string有没有相同的。

代码如下:

class Solution {
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> res = new LinkedList<>();
        postorder(root, new HashMap<>(), res);
        return res;
    }

    public String postorder(TreeNode cur, Map<String, Integer> map, List<TreeNode> res) {
    	if(cur == null)
    		return "#";
    	//将二叉树的信息转化为string
    	String serial = cur.val + "," + postorder(cur.left, map, res) + "," + postorder(cur.right, map, res);
    	//将节点加入list
    	if(map.getOrDefault(serial, 0) == 1)
    		res.add(cur);
    	//更新map
    	map.put(serial, map.getOrDefault(serial, 0) +1);
    	return serial;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值