Given the root of 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 the same node values.
Example 1:

Input: root = [1,2,3,4,null,2,4,null,null,4] Output: [[2,4],[4]]
Example 2:

Input: root = [2,1,1] Output: [[1]]
Example 3:

Input: root = [2,2,2,3,null,3,null] Output: [[2,3],[3]]
Constraints:
- The number of the nodes in the tree will be in the range
[1, 10^4] -200 <= Node.val <= 200
题目链接:https://leetcode.com/problems/find-duplicate-subtrees/
题目大意:求完全相同的子树
题目分析:序列化枚举判断即可,向左加'l',向右加'r',遇空加'n',递归的时候将每个孩子都当作当前的子树根来看待,节点并不是根据其value值判相等,需要用一个map记录当前的序列化串出现的次数,为2时记一次答案即可
11ms,时间击败98.38%
/**
* 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> mp = new HashMap<>();
public String dfs(TreeNode root, StringBuilder sb, List<TreeNode> ans) {
if (root == null) {
return "n";
}
sb.append(root.val);
sb.append("l").append(dfs(root.left, new StringBuilder(""), ans));
sb.append("r").append(dfs(root.right, new StringBuilder(""), ans));
String cur = sb.toString();
mp.put(cur, mp.getOrDefault(cur, 0) + 1);
if (mp.get(cur) == 2) {
ans.add(root);
}
return cur;
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
List<TreeNode> ans = new ArrayList<>();
dfs(root, new StringBuilder(""), ans);
return ans;
}
}

该博客介绍了一种解决LeetCode上的'找重复子树'问题的方法,通过序列化二叉树节点,利用HashMap记录出现频率,当频率为2时找到重复子树。代码实现中,使用深度优先搜索(DFS)进行遍历,并给出了Java解决方案,具有良好的时间复杂度。
1127

被折叠的 条评论
为什么被折叠?



