All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0601_0700.s0652_find_duplicate_subtrees.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0601_0700.s0652_find_duplicate_subtrees;

// #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree

import com_github_leetcode.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List findDuplicateSubtrees(TreeNode root) {
        Map map = new HashMap<>();
        List list = new ArrayList<>();
        helper(root, map, list);
        return list;
    }

    private String helper(TreeNode root, Map map, List list) {
        if (root == null) {
            return "#";
        }
        String key =
                helper(root.left, map, list) + "#" + helper(root.right, map, list) + "#" + root.val;
        map.put(key, map.getOrDefault(key, 0) + 1);
        if (map.get(key) == 2) {
            list.add(root);
        }
        return key;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy