加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

652. Find Duplicate Subtrees - Medium

发布时间:2020-12-14 05:15:48 所属栏目:大数据 来源:网络整理
导读:Given a binary tree,return all duplicate subtrees. For each kind of duplicate subtrees,you only need to return the root node of any?one?of them. Two trees are duplicate if they have the same structure with same node values. Example 1: 1 /

Given a binary tree,return all duplicate subtrees. For each kind of duplicate subtrees,you only need to return the root node of any?one?of 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.

?

给每个subtree赋一个unique id,如果两个子树的id相同,说明duplicate。

需要用两个hashmap,一个把subtree serialize成string,存<string,id>,另一个计数,每个id出现多少次。最后遍历计数map,如果出现两次就放进res里

time: O(n),space: O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map<String,Integer> map;
    Map<Integer,Integer> count;
    List<TreeNode> res;
    int t;
    
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        map = new HashMap<>();
        count = new HashMap<>();
        t = 1;
        
        getId(root);
        return res;
    }
    
    public int getId(TreeNode root) {
        if(root == null) {
            return 0;
        }
        String serialize = root.val + "," + getId(root.left) + "," + getId(root.right);
        int uid = map.computeIfAbsent(serialize,k -> t++);
        count.put(uid,count.getOrDefault(uid,0) + 1);
        if(count.get(uid) == 2) {
            res.add(root);
        }
        return uid;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读