1. 程式人生 > >652. Find Duplicate Subtrees - Medium

652. Find Duplicate Subtrees - Medium

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; } }