给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
两棵树重复是指它们具有相同的结构以及相同的结点值。
示例 1:
1
/ \
2 3
/ / \
4 2 4
/
4
下面是两个重复的子树:
2
/
4
和
4
因此,你需要以列表的形式返回上述重复子树的根结点。
Related Topics
class Solution {
private List<TreeNode> res = new ArrayList<>();
private Map<String, Integer> memo = new HashMap<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
serializeNode(root);
return res;
}
private String serializeNode(TreeNode root) {
if (root == null) {
return "#";
}
String left = serializeNode(root.left);
String right = serializeNode(root.right);
// 序列化二叉树
String curr = left + "," + right + "," + root.val;
Integer count = memo.getOrDefault(curr, 0);
if (count == 1) {
res.add(root);
}
memo.put(curr, count + 1);
return curr;
}
}
Post Views: 158