给定一棵二叉树 root,返回所有重复的子树。 对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。如果两棵树具有相同的结构和相同的结点值,则它们是重复的。
提示:
- 树中的结点数在 [ 1 , 1 0 4 ] [1,10^4] [1,104]范围内。
- − 200 ≤ N o d e . v a l ≤ 200 -200 \leq Node.val \leq 200 −200≤Node.val≤200
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<TreeNode> res = new ArrayList<>();
Map<String,Integer> map = new HashMap<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return res;
}
public String dfs(TreeNode root) {
if(root == null) {
return "null";
}
String s = String.valueOf(root.val) + "," + dfs(root.left) + "," + dfs(root.right);
map.put(s, map.getOrDefault(s, 0) + 1);
if(map.get(s) == 2) {
res.add(root);
}
return s;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<String,Integer> map = new HashMap<>();
Map<Integer,Integer> cnt = new HashMap<>();
List<TreeNode> res = new ArrayList<>();
int count = 0;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return res;
}
public int dfs(TreeNode root) {
if(root == null) {
return 0;
}
int l = dfs(root.left), r = dfs(root.right);
String s = String.valueOf(root.val) + " " + String.valueOf(l) + " " + String.valueOf(r);
if(map.get(s) == null) {
map.put(s, ++count);
}
int idx = map.get(s);
cnt.put(idx, cnt.getOrDefault(idx, 0) + 1);
if(cnt.get(idx) == 2) {
res.add(root);
}
return idx;
}
}