[LeetCode] 652. Find Duplicate Subtrees

linspiration

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;
    }
}
阅读 1.2k

Road to Glory
對酒當歌,人生幾何?譬如朝露,去日苦多。
161 声望
31 粉丝
0 条评论
161 声望
31 粉丝
宣传栏