给定一棵二叉树 root,返回所有重复的子树。
对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
如果两棵树具有相同的结构和相同的结点值,则它们是重复的。
/**
* 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 {
HashMap<String,Integer> map;
List<TreeNode> res;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
map = new HashMap<String,Integer>();
res = new ArrayList<>();
findhelper(root);
return res;
}
public String findhelper(TreeNode root){
if(root == null){
return "#";
}
String left = findhelper(root.left);
String right = findhelper(root.right);
String subTree = left + "," + right + "," + root.val;
int freq = map.getOrDefault(subTree,0);
if(freq == 1){
res.add(root);
}
map.put(subTree,freq+1);
return subTree;
}
}
执行用时:20 ms, 在所有 Java 提交中击败了82.30%的用户
内存消耗:45.6 MB, 在所有 Java 提交中击败了70.48%的用户
通过测试用例:176 / 176