0%

Leetcode652-findDuplicateSubtrees

Description

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
2
3
4
5
6
7
    1
/ \
2 3
/ / \
4 2 4
/
4

The following are two duplicate subtrees:

1
2
3
  2
/
4

and
1
4

Therefore, you need to return above trees’ root in the form of a list.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
HashMap<String, Integer> map = new HashMap<>();
List<TreeNode> res = new ArrayList<TreeNode>();
helper(root, map, res);
return res;
}

private String helper(TreeNode node, HashMap<String, Integer> map, List<TreeNode> res){
if (node == null) return "#";
String cur = node.val + "-" + helper(node.left, map, res) + "-" + helper(node.right, map, res);
if (map.getOrDefault(cur, 0) == 1) res.add(node);
map.put(cur, map.getOrDefault(cur, 0) + 1);
return cur;
}
}