652. 寻找重复的子树
作者:互联网
给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
两棵树重复是指它们具有相同的结构以及相同的结点值。
示例 1:
1
/ \
2 3
/ / \
4 2 4
/
4
下面是两个重复的子树:
2
/
4
和
4
因此,你需要以列表的形式返回上述重复子树的根结点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-duplicate-subtrees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
深度优先搜索
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
private List<TreeNode> ans = new ArrayList<>();
private Map<String, Integer> cntMap = new HashMap<>();
private String solve(TreeNode root) {
if (root == null) {
return "#";
}
String series = root.val + "+" + solve(root.left) + "+" + solve(root.right);
Integer cnt = cntMap.getOrDefault(series, 0);
if (cnt == 1) {
ans.add(root);
}
cntMap.put(series, cnt + 1);
return series;
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
solve(root);
return ans;
}
}
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;
}
}
唯一标识符号
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
int t;
Map<String, Integer> trees;
Map<Integer, Integer> count;
List<TreeNode> ans;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
t = 1;
trees = new HashMap();
count = new HashMap();
ans = new ArrayList();
lookup(root);
return ans;
}
public int lookup(TreeNode node) {
if (node == null) {
return 0;
}
String serial = node.val + "," + lookup(node.left) + "," + lookup(node.right);
int uid = trees.computeIfAbsent(serial, x -> t++);
count.put(uid, count.getOrDefault(uid, 0) + 1);
if (count.get(uid) == 2)
ans.add(node);
return uid;
}
}
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;
}
}
标签:子树,TreeNode,val,重复,int,right,652,root,left 来源: https://www.cnblogs.com/tianyiya/p/15788668.html