1. 程式人生 > 實用技巧 >652. Find Duplicate Subtrees

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

class Solution {
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> res = new ArrayList();
        helper(root, res, 
new HashMap()); return res; } public String helper(TreeNode root, List<TreeNode> res, Map<String, Integer> map) { if(root == null) return ""; String s = root.val + "," + helper(root.left, res, map) + "," +helper(root.right, res, map);
if(map.getOrDefault(s, 0) == 1) res.add(root); map.put(s, map.getOrDefault(s, 0) + 1); return s; } }

用一個hashmap記錄每個node對應的hash string的頻率(hash就是root val string加上它的左右子,很玄學,記得要加個逗號)。

然後這個實際上是一個postorder新增到map中,但看起來hash的時候是preorder,如果這個hash出現了一次就要把這個root新增到res中