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;
}
}