[LeetCode] 652. Find Duplicate Subtrees

发布于:2023-05-25 ⋅ 阅读:(62) ⋅ 点赞:(0)

Problem

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.

Solution

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

网站公告

今日签到

点亮在社区的每一天
去签到